Compose is the future of Android UI
Tuesday, April 6, 2021When I first saw Compose I thought "why would I want this".
XML works. ConstraintLayout is good. Databinding handles the state stuff. Why change?
Then I actually used it.
No more XML
This is a button in Compose:
Button(onClick = { doSomething() }) {
Text("Click me")
}
No XML file. No findViewById. No binding class. Its just Kotlin.
State is simple
In the old world you have to manually update views when data changes:
viewModel.user.observe(this) { user ->
nameTextView.text = user.name
emailTextView.text = user.email
avatarView.load(user.avatar)
}
In Compose:
@Composable
fun UserCard(user: User) {
Column {
Text(user.name)
Text(user.email)
Avatar(user.avatar)
}
}
When user changes, the UI updates automatically. You dont call setText or anything. It just happens.
The weird parts
Recomposition took time to understand. Your function can be called multiple times and you need to write it in a way that handles that.
Also previews are slow. Really slow on my laptop. Maybe better now, I wrote this in 2021.
Worth it?
Yes. After the initial learning curve everything is faster. Building UI, changing UI, testing UI.
I dont want to go back to XML. Compose is how Android UI should have been from the start.