View binding : Android
Wow! yes you read it right. This was my reaction when I first read about View Binding and it’s usage.
Below are some questions which will be resolved if you read the blog.
- What is View Binding?
- How it is different from
findViewById
? - Implementing View Binding in
- Activities
- Fragments - Link to some resources and Sample Projects.
Let’s get Started
What is View Binding?
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. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout.
In most cases, view binding replaces
findViewById
.
In some simple words, For each XML file that we have in our project, View Binding generates a binding class, the instance of the binding class have direct references to the views that are present in the XML file and have an ID.
Let’s understand this with an example:
In activity_main.xml, we have a TextView with id tvName.
that TextView can be referenced in our Java/Kotlin…