View Binding in Andorid

Introduction 

View Binding is a new feature of Android. View binding allows us to replace the findViewById() method in most cases. View binding allows us to write code more easily and access directly views. Suppose we have 10 views in a particular activity so we need to initialize these views using the findViewById() method. This will take extra time and code length also increase so it's better to use view binding and access directly views. 

How To Implement View Binding In Android 

Step 1

Create a new project in android studio and select Empty Activity

 

Step 2

Go to build. gradle(Module), find  android{ } and add the below code inside this.

viewBinding{
    enabled=true
}

After adding the above code, press the Sync Now button. This button is visible in the right-top corner of android studio.

Step 3

Once the above step is performed then view binding generates a binding class for each XML layout. For example, view binding generates ActivityMainBinding class for activity_main.xml. By default, we get a textview in the activity_main.xml so just give an id to this textview.

 <TextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

Step 4

Go to MainActivity.java and create an ActivityMainBinding class object.

ActivityMainBinding binding;

Step 5

Inside onCreate() method, add the below code

binding=ActivityMainBinding.inflate(getLayoutInflater());
View view=binding.getRoot();

Step 6

Inside onCreate() method, add the below code

setContentView(view);

Before adding this code we need to delete the previous setContentView().

Step 7

We can directly access the views without using the findViewById() method. For accessing the textview that is present in activity_main.xml write the below code. 

binding.textview.setText("Hello Android");

Here, binding is the object of ActivityMainBinding class and textview is the id of TextView.

Output

 

 

Advantages of View Binding

  • Null Safety - there's no risk of a null pointer exception due to an invalid view id.
  • Type Safety -  there's no risk of class cast exception.
  • Fast Compilation - since we can access directly views by using view binding so compilation process is fast as compared to the findViewById() method.

Conclusion

In this article, we have seen what is view binding and how to use view binding in android. Thanks for reading and hope you like it. If you have any suggestions or queries on this article, please share your thoughts.


Similar Articles