Replace FindViewByID with ViewBinding in Java on Android

In the gradle.build file for the module, add following code and Sync:

buildFeatures {
   viewBinding true
}

Above automatically generates binding objects for every layout when the plugin is synced. For activity_main.xml, it will generate ActivityMainBinding class.

In MainActivity.java, use inflate method on ActivityMainBinding in onCreate method as shown below:

ActivityMainBinding bindMain;
bindMain = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(bindMain.getRoot());

Note that layout is stored in a special property called root.

ViewBinding only creates views for views with IDs only. If layout file was named help_activity.xml, then helpActivityBinding would have been auto-created.

ViewBinding with included xml layout files

When you have XML layout files like activity_main_may.xml that are included into the activity_main.xml, and you want to use ViewBinding, then give an ID to the layout include statement as illustrated below for activity_main_may.xml.

<include android:id="@+id/maylayout"
layout="@layout/activity_main_may"/>

Then, in MainActivity.java do following:

ActivityMainBinding bindMain;
TextInputEditText m_may_contrib;

In onCreate() method, do following:

bindMain = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(bindMain.getRoot());

Use maylayout as shown below to fetch it’s views:

m_may_contrib = bindMain.maylayout.mayContrib;

Now app will work with included layouts. Remember that only views with IDs work with ViewBinding.

These video, this video and this video explained the ViewBinding concept very well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s