How To: View Binding in Android

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

Leave a Reply

Your email address will not be published. Required fields are marked *