Android — How to use ViewBinding

Konstantinos Evangelidis
2 min readFeb 26, 2021

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 tools:viewBindingIgnore="true" attribute to the root view of that layout file:

<androidx.constraintlayout.widget.ConstraintLayout
...
tools:viewBindingIgnore="true" >
...
</androidx.constraintlayout.widget.ConstraintLayout>

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

setContentView(binding.root)

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

<TextView
android:id="@+id/simple_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
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

with(binding){
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.

binding.simpleText.apply{
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.

Enjoy.

--

--