Replace findViewById with View Binding

Perhaps you have code that looks like that:

val mImageView = findViewById<ImageView>(

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


Enable View Binding in gradle:

android {
    buildFeatures {
        viewBinding true


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