View Binding: Good Replacement of findViewById() in Android

Dr. Vipin Kumar
4 min readApr 27, 2021

View binding is a feature in Android Programming that allows you to replace findViewById(), and write your code more easily that interacts with views. Once view binding is enabled in a module, it generates automatically 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.

It works on android studio version 3.6 or above.

View Binding Advantages Over findViewById

View binding has important advantages over using findViewById:

1. Null safety: View binding creates direct references to views, so there’s no risk of a null pointer exception due to an invalid view ID. Additionally, when a view is only present in some configurations of a layout, the field containing its reference in the binding class is marked with @Nullable.

2. Type safety: No risk of class cast exception, fields in each binding class have types matching the views they reference in the XML file.

View Binding Comparison with Data Binding

Both, View binding and data binding both generate binding classes. However, view binding provides the following benefits over data binding:

1. Faster compilation: View binding requires no annotation processing, so compile times are faster.

2. Ease of use: View binding does not require specially-tagged XML layout files, so it is faster to adopt in your apps. Once you enable view binding in a module, it applies to all of that module’s layouts automatically.

View Binding Limitations Compared to Data Binding

1. View binding doesn’t support layout variables or layout expressions, so it can’t be used to declare dynamic UI content straight from XML layout files.

2. View binding doesn’t support two-way data binding.

Because of these considerations, it is best in some cases to use both view binding and data binding in a project. You can use data binding in layouts that require advanced features and use view binding in layouts that do not.

Configuration Steps

Step 1: Enabling ViewBinding in Module-Level Gradle File

Firstly, we need to enabling view binding in a module, for that we need to set the viewBinding build option to true in the module-level build.gradle file, as shown in the example below:

For Version 3.6 but less than 4.0:

android {

viewBinding {
enabled = true
}
}

For Version 4.0 & Above:

android {

buildFeatures {
viewBinding true
}
}

But, 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:

<LinearLayout

tools:viewBindingIgnore=”true” >

</LinearLayout>

Step 2: Understanding Automatic Class Generation for all Layout Files:

When view binding is enabled for a module, a binding class is generated automatically for each XML layout file. Each binding class contains references to the root view and all views that have an ID. The name of the binding class is generated by converting the name of the XML file to Pascal case and adding the word “Binding” to the end.

For example, if layout file name is activity_main.xml then binding class named would be ActivityMainBinding, and as per more example given in table below:

Automatically Generated View Binding Class Name

Every generated binding class have getRoot() method, this method provides direct reference for the root view of the corresponding layout file. This method we need to pass to setContextView() function, see example in View Binding in Activity Heading.

Step 3 (For Activity): View Binding in Activity

Perform the following 2 steps in the your activity onCreate() method for setting up an instance of the binding class:

1. Call the static inflate() method included in the generated binding class ActivityMainBinding. This creates an instance of the binding class for the activity to use.

2. Pass the getRoot() method reference to setContentView() to make it the active view on the screen.

Layout File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">    <TextView        android:id="@+id/txtmsg"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>

Java Code:

private ActivityMainBinding binding;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    binding = ActivityMainBinding.inflate(getLayoutInflater());setContentView(binding.getRoot());}

After binding, now you can use the instance of the binding class to reference any of the views like as shown below for TextView:

binding.setmsg.setText(“Hello World”);

Kotlin Code:

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)

setContentView(binding.root)
}

After binding, now you can use the instance of the binding class to reference any of the views like as shown below for TextView:

binding.txtmsg.text = “Hello World”

Step 3 (For Fragment): View Binding in Fragment

Perform the following 2 steps in the your fragment onCreateView() method for setting up an instance of the binding class:

1. Call the static inflate() method included in the generated binding class FragmentOneBinding. This creates an instance of the binding class for the activity to use.

2. Return the getRoot() method reference from the setContentView() to make it the active view on the screen.

Java Code:

private FragmentOneBinding binding;//Fragment name is Fragment_One.xml@Overridepublic View onCreateView (LayoutInflater inflater,                           ViewGroup container,                           Bundle savedInstanceState) {    binding = FragmentOneBinding.inflate(inflater, container, false);    View view = binding.getRoot();    return view;}@Overridepublic void onDestroyView() {    super.onDestroyView();    binding = null;}

Kotlin Code:

private var _binding: FragmentOneBinding? = null// This property is only valid between onCreateView and// onDestroyView.private val binding get() = _binding!!override fun onCreateView(    inflater: LayoutInflater,    container: ViewGroup?,    savedInstanceState: Bundle?): View? {    _binding = FragmentOneBinding.inflate(inflater, container, false)    val view = binding.root    return view}override fun onDestroyView() {    super.onDestroyView()    _binding = null}

--

--

Dr. Vipin Kumar

Assoc. Prof. , DCA & Assoc. Head (SD), SDFS, at KIET, PhD (CS) My YouTube Channel: Dr. Vipin Classes (https://www.youtube.com/channel/UC-77P2ONqHrW7h5r6MAqgSQ)