AndroidPub
Published in

AndroidPub

Jetpack Compose — Android Apps without XML

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!

--

--

--

The (retired) Pub(lication) for Android & Tech, focused on Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Burak Eregar

Burak Eregar

Senior Android Engineer @Onfido https://github.com/burakeregar/

More from Medium

Getting prepared for Jetpack Compose

Jetpack Compose Tutorial

Understanding of Coroutine Scope Behavior for Fragment

Getting Started with ConstraintLayout in Jetpack Compose

Cancelling Kotlin Coroutines