Reduce ViewBinding code boilerplates with Kotlin Property Delegate.
Introduction to ViewBinding
ViewBinding is a new feature of Android Gradle Plugin which allows you to access view hierarchy with type and null safety. ViewBinding is integrated with the Android Gradle Plugin directly, so it doesn’t depend on Annotation Processing (KAPT) as Butterknife does. Also, it much safer and cheaper than Kotlin Synthetic which uses HashMap<Int, View> under the hood.
ViewBinding is not enabled by default in Android Studio 4.1 with AGP (4.1.0), so it has to be enabled manually in
build.gradle of the app module.
After enabling it, we will be able to access generated ViewBinding classes inside our Activity/Fragment.
The generated class names will be in PascalCase linked to
snake_case xml resource files. For example, if we have
activity_main.xml the generated class will be
ActivityMainBinding , and if we have
fragment_home the class will be
FragmentHomeBinding . I hope you get the point!
There are two ways to construct a ViewBinding instance. The first one is to inflate the view from the XML layout by calling
ViewBinding.inflate(inflater: LayoutInflater) or
ViewBinding.inflate(inflater: LayoutInflater, parent: ViewGroup?, attachToRoot: Boolean) . The second way is to bind with the existing view by calling
ViewBinding.bind(view: View) .
The first option is a recommended way to inflate view since it gives us a single source of truth, however, in some cases, we cannot inflate it, so we bind it instead.
Calling Children Views
All views with the ID specified will be generated inside the ViewBinding class as final read-only fields. You can call them by
ViewBinding#myButton . The ViewBinding holds strong references to all view fields.
In this case, we have a child button with an ID:
@+id/button_say_hello , so the generated field will be
Reduce Code Boilerplates
In these examples, we have to quite a bit of code in order to get the ViewBinding instance and set it into an Activity. Let’s do something to make it shorter and more concise.
We can achieve this by using Kotlin Property Delegate & Android Lifecycle Observer.
The final result looks like this:
This property delegate will automatically inflate itself and
setContentView to the Activity for you, so you don’t have to do it by yourself. Pretty cool huh?
ViewBinding inside Fragment
In Fragment, we have extra work to do in order to avoid memory leaks by setting the ViewBinding reference to
onDestroyView method. As I mention, ViewBinding holds strong references of views so use it wisely.
A small leak will sink a great ship. — Benjamin Franklin
ViewBinding is currently the best way to access view hierarchy since it guarantees type-safety and compile-time errors unlike Butterknife & Kotlin Synthetic.