View binding is a feature that allows you 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.

  1. Add this in to app module build.gradle in android under buildFeatures:

  1. Create layout file – activity_main.xml:

  1. In the MainActivity we need to declare this layout root element as class:

  • note: the class name for this binding to work needs to have the layout file name and word binding together with camel case.
    In our case activity_main + binding = ActivityMainBinding class name.

and to set in in onCreate():

  1. Actual binding of the view declared in the activity_main.xml:

Why View Binding over natieve findViewById, ButterKnife library (apart that is now deprecated), Kotlin Synthetic, Data Binding:

1_lZsHEB7MOcgSd5dE64Nu8Q

 

Documentation:
https://developer.android.com/topic/libraries/view-binding 1

Part of Jetpack for Android:
https://developer.android.com/jetpack

Spread the love

Leave a Reply

Your email address will not be published.