Replace FindViewByID with ViewBinding in Java on Android

In the 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, use inflate method on ActivityMainBinding in onCreate method as shown below:

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

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"

Then, in do following:

ActivityMainBinding bindMain;
TextInputEditText m_may_contrib;

In onCreate() method, do following:

bindMain = ActivityMainBinding.inflate(getLayoutInflater());

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.