This is an Android library. It makes your life easier by reducing boilerplate code and avoiding redundant lines of code when are using the ViewBinding feature on your Android project. This library show up in my head as an very good example on how the property delegation functionality from kotlin can help us.
Binding
Yes, the
viewBinding()
method will bind to the root view for you.
class MainActivity : AppCompatActivity(R.layout.activity_main) {
private val binding : ActivityMainBinding by viewBinding()
}
Inflating
You don't need to set the layout calling
setContentView()
. It will be done automatically.
class MainActivity : AppCompatActivity() {
private val binding : ActivityMainBinding by viewBinding(ViewBindingMethod.INFLATE)
}
Binding
The
viewBinding()
method will track the fragment view lifecycle and destroy the ViewBinding instance for you.
class MyFragment : Fragment(R.layout.fragment_layout) {
private val binding by viewBinding<FragmentLayoutBinding>()
}
Inflating
Using this way, it gives you the
onCreateView
class MyFragment : Fragment() {
private val binding by viewBinding<FragmentLayoutBinding>(ViewBindingMethod.INFLATE)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = binding.root
}
Add the following dependency to your build.gradle
file:
dependencies {
implementation 'com.github.jrvansuita:view-binding:1.0.2'
}
Don't forget to add the JitPack maven repository to the list of repositories:
maven { url "https://jitpack.io" }