Replace findViewById with View Binding

Perhaps you have code that looks like that:

val mImageView = findViewById<ImageView>(R.id.img_view)
mImageView.setOnClickListener(View.OnClickListener

This has worked properly over the last years but what are the drawbacks?

Or what are the promises of the new View Binding concept?

  • View Binding is always null-safe and type-safe
  • It compiles faster

Gradle

Enable View Binding in gradle:

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

Implementation

In your Fragment or Activity you need to instantiate the View Binding class for your layout:

private var _binding: YourFragmentBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
_binding = YourFragmentBinding.inflate(inflater, container, false)

Now you can use it as follows:

binding.imgView.setOnClickListener {

Instead of searching via findViewById ViewBinding generates properties which you can access directly.

Further Reading

https://medium.com/androiddevelopers/use-view-binding-to-replace-findviewbyid-c83942471fc