Jetpack Compose is the way. But sometimes, you still need Fragments and XML. And if you have to deal with that, you’ll probably want to use view binding. Writing this quick reminder for my future self for when I find myself in that predicament.
To enable view binding, add the following to your module build.gradle file:
android {
...
buildFeatures {
viewBinding = true
}
}
This automatically generates a binding class for each layout. In my example activity_whatever.xml
becomes ActivityWhateverBinding
.
Then in your Activity
(AppCompatActivity
in this case) declare a lazy val
for your binding
and inflate it. Then setContentView
to binding.root
.
class WhateverActivity: AppCompatActivity() {
private val binding: ActivityWhateverBinding by lazy { ActivityWhateverBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
}
}
This is a super quick & easy way to bind your XML. So simple that you’ll avoid the urge to setup some base class just for making binding easier. If you were using a different Activity type, this also makes it easier to move to AppCompatActivity
or ComponentActivity
in the future to enable Hilt.