viewBinding

View Binding is a part of Android Jetpack and allows us to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module.

Each binding class contains references to the root view and all views that have an ID. The name of the binding class is generated by converting the name of the XML file to Pascal case and adding the word “Binding” to the end. For example, if a layout file is called activity_main.xml the genereted binding class will be called ActivityMainBinding

Instead using findViewById() method we can use viewBinding to access elements in Kotlin .xml file.

First we have to add viewBinding true in app/build.gradle file:

android {
  // …
   buildFeatures {
       viewBinding = true
   }
 }

To set up an instance of the binding class for use with an activity, in MainActivity.kt onCreate() method we have to write code:

class MainActivity : AppCompatActivity() {

   private lateinit var binding: ActivityMainBinding

   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)

         binding = ActivityMainBinding.inflate(layoutInflater)
         val view = binding.root

      setContentView(view)
   }
 }

We can now use the instance of the binding class to reference any of the views, for example:

binding.tv_title.text = "Title"
binding.name.text = viewModel.name
binding.button.setOnClickListener { viewModel.userClicked() }
binding.imageButton.visibility = View.VISIBLE

View binding has important advantages over using findViewById:
Since view binding creates direct references to views, there’s no risk of a null pointer exception due to an invalid view ID. Additionally, when a view is only present in some configurations of a layout, the field containing its reference in the binding class is marked with @Nullable.
The fields in each binding class have types matching the views they reference in the XML file. This means that there’s no risk of a class cast exception.
Incompatibilities between layout and code will result in build failing at compile time rather than at runtime.