Android — How to use ViewBinding

Hello world. In this tutorial we are gonna learn how to use ViewBinding since as a Android developer we have to forgot about findById or synthetics.

What is the ViewBinding and how it works?

First of all ViewBinding is part of Android Jetpack.
ViewBinding is a feature that allows you more easily manage your XML layouts inside the app. Once the viewBinding is enabled, it generates a binding class for each XML layout file. So at the end you will have a binding class contains references to all views that have an ID in the layout.

How to setup viewBinding?

All you need is to add this lines in module-level build.gradle inside android region.

android {
buildFeatures {
viewBinding true

As we said viewBinding is generating a class for each XML layout. If you want a layout file to be ignored while generating binding classes, add the attribute to the root view of that layout file:

tools:viewBindingIgnore="true" >

How to use viewBinding?

First step is to create a variable inside activity. You have to be careful to use the correct class name. For example if the activity’s name is MainActivity the generated class named ActivityMainBinding. If the activity is LocationActivity the binding class named ActivityLocationBinding. So create a variable like this

private val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }

And inside onCreate change the setContentView to this


Next step is to manage the views inside the XML file. If for example we have this textView inside the XML

app:layout_constraintTop_toTopOf="parent" />

all we need to use is binding.simpleText

For example to set text

binding.simpleText.text = "Hello viewBinding. I love you."

Other examples

binding.simpleText.setOnClickListener { … }
binding.simpleText.visibility = View.VISIBLE

Bonus tips to make your code looks better

simpleText.text = "Hello viewBinding. I love you."
simpleText.setOnClickListener { … }
simpleText.visibility = View.VISIBLE
otherText.text = "Hello again!!!"

Like this you dont have to the wold binding aver and over.

text = "Hello viewBinding. I love you."
setOnClickListener { … }
visibility = View.VISIBLE

You can use this logic if you have to use the same view multiple times.

Hope you like this article about ViewBinding.




Android Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store