how to use ViewBinding in android studio 3.6| replaces findViewById in android studio

Опубликовано: 04 Март 2025
на канале: Android Development Tutorials
60
0

View Binding in android

1. View Binding is a feature that allows you to replace findViewById in
most cases. Once view Binding is enabled in a module, it generates a binding class for each xml layout file present in that module.

2.For example- if you have xml layout file named activity_main.xml
viewBinding will generate ActivityMainBinding class for you.

3.An instance of a binding class contains direct references to all views
that have an ID in the corresponding layout.

4.View Binding is available in Android Studio 3.6 Canary 11+

5. View binding is enabled on a module by module basis. To enable view binding in a module, add the viewBinding element to its build.gradle file, as shown in the following example:

android {
...
viewBinding {
enabled = true
}
}

View binding has important advantages over using findViewById:

1. Null safety: Since view binding creates direct references to views, 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: The fields in each binding class have types matching the views they reference in the XML file. This means that there's no risk of a class cast exception.

ViewBinding Documentation-

https://developer.android.com/topic/l...