How to use view binding in android studio kotlin
How to use View Binding in Android using Kotlin
In Android Studio 4.1+, when you create a new Kotlin project and try to connect an XML layout file with your .kt file using Kotlinx synthetic, you’ll see you can’t do it anymore.
This is because they removed the plugin ‘Kotlin Android Extensions‘ as JetBrains deprecated it in the 1.4.20 version of Kotlin.
Now, the alternatives are:
- ButterKnife
- findViewById()
- View Binding
Enabling View Binding
In your module-level build.gradle file, add the following code to enable view binding
This automatically will create binding classes for each XML file present in that module.
For example, if an XML file name is activity_main.xml, the generated binding class will have the name of this file in Pascal case and the word ‘Binding‘ at the end.
So the binding class will be ActivityMainBinding.
If you don’t want to generate a binding class for a specific XML file, add the attribute tools:viewBindingIgnore="true" in the root layout like that:
Using View Binding in Activities
To use View Binding in Activity, create an instance of the binding class, get the root view, and pass it to setContentView().
Now, you can reference your views like that:





Comments
Post a Comment