Android: View Binding

In your app build.gradle file, add the following lines to the “android” section:

buildFeatures {
    viewBinding = true
}

In your main class, create a member variable called, “binding”, where the name of the binding class is the name of the layout converted to camelCase:

 lateinit var binding: ActivityMainBinding

In onCreate(), initialize the view binding:

binding = ActivityMainBinding.inflate(layoutInflater)

Call setContentView with “binding.root” instead of the main layout file:

setContentView(binding.root)

Now you can access views using the binding object like this, where the name of the view is its id converted to camelCase.:

binding.myViewId