Android View Binding

ViewBinding is a feature that allows you to more easily write code (less boilerPlate code) that interacts with the views from the XML file directly in the class.
In most cases, view bindings replaces findViewById()

Once viewBinding is enabled, inside the module build.gradle file:



An instance of a binding class contains direct references to all views that have an id in the corresponding layout.
For example:

For Activities:


For Fragments:


From Android Developers documentation:

Note: Fragments outlive their views. Make sure you clean up any references to the binding class instance in the fragment’s onDestroyView() method.

The main differences of view binding from findViewById() are:

1. Type safety: there’s no risk of a class cast an exception
2. Null safety: viewBinding creates direct reference to the views in the XML file which means there’s no risk to get a null pointer exception.


Leave a Reply