View Binding
A note about the view binding feature (Android Studio 3.6+)
Since Developing Android Apps with Kotlin has launched, a new feature, view binding, has been introduced and is available in Android Studio 3.6 and higher. We don't use view binding because it came out after the course, but it's a feature to be aware of.
View binding replaces findViewById
. View binding generates a binding object for each XML layout. You use this binding object to reference views, using their resource ids as the name:
// Creating a binding object for the main_activity.xml layout binding = ActivityMainBinding.inflate(layoutInflater) // Referencing a view with the ID roll_button binding.rollButton
View binding has the following benefits over findViewById
:
- Type safety -
findViewById
requires you to specify the type of view you expect to be returned. For example, if you accidentally specify that you expect anImageButton
to be returned when the actual type is aButton
, you'll get a ClassCastException. View binding protects you from this type of error because the view is a correctly typed property of the binding. - Null safety -
findViewById
expects an integer parameter, which is meant to be the resource ID of a view. It is possible, though, to pass in any integer as a parameter, including unrelated integers and invalid view ids. If you supply an integer that doesn't match a view resource id in the layout,findViewById
returns null and can cause aNullPointerException
. View binding is null safe because you reference view objects directly and don't look them up by integer IDs.
Comments
Post a Comment