Jetpack Compose — Android Apps without XML

Burak Eregar
AndroidPub
Published in
2 min readMay 8, 2019

--

Source: Jetpack Hero by Google

What is Jetpack Compose?

Jetpack Compose has been announced by Google at Google I/O 2019.

Jetpack Compose is an unbundled toolkit designed to simplify UI development. It combines a reactive programming model with the conciseness and ease of use of the Kotlin programming language.

Jetpack Compose has two major components which are:

  • Compose UI Library
  • Compose Compiler

Both of them live in the Android Open Source Project and all the code can be found here and here.

How does it work under the hood?

A custom Kotlin compiler plugin reads all the functions with @Composable annotation which are pure functions and transforms them into a UI hierarchy. As they are pure functions, they should be side-effect free, which means we are not able to use global or static variables, hence, we need to pass the data directly to the function.

What does the code look like?

@Composable
fun Greeting(name: String) {
Text ("Hello $name!")
}

The code above will generate a TextView and set the name property to it.

Now we can use it in our Activity. From now on, we don’t need to call setContentView and pass the XML layout file. Instead, we create our Kotlin DSL block and put our scaffold like below.

class Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

setContent {
Scaffold {
Greeting("Adam Smith")
}
}
}
}

Benefits

  • 100% Kotlin 😎
  • It is not part of Android OS which would allow us to keep the same minSdkVersion when we face a bug in the library as it would be fixed separately in the next versions of Jetpack Compose Library.
  • No need to write XML anymore.
  • Can be part of our lovely Android Architecture!
  • Potential flexible reusability ❤
  • It is part of AOSP, therefore, anyone can contribute to it.

Can I use it on my prod app?

Since it is still experimental and in an early-exploration pre-alpha stage, it should not be used in a production app for now.

P.S: Since it is a very early stage of this library, I am planning to keep this blog post updated. I will also provide a sample project soon.

Thanks for reading!

You can follow me on GitHub and Twitter!

--

--