Android View Binding Without Boilerplate — Part 2
In part 1, I showed you how to use a delegate with a lifecycle observer to reduce your fragment view binding code from
to
Now we’re going to reduce this much further by using a base class. The disadvantage of such an approach is that, well, we need a base class. Using inheritance can allow code reuse but decreases flexibility. So I can’t automatically recommend this over the approach in part 1, but it’s quite nice to get rid of almost everything, behold.
And here is the code for ViewBindingFragment.
Diving into Binding
From the android documentation:
Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module.
If you’re curious, here is the ViewBinding interface that all generated Binding classes implement.
Note, there is no inflate function in it. This is annoying and this is why we must pass the inflate function everytime. My best guess for why the inflate function isn’t included is because the signature of the inflate function can actually change depending on if the root tag of a layout is merge or not. Fragments can’t inflate and return a layout with a merge root tag, Android will throw a crash one way or another if you try, so we don’t have to worry about it much.
Lastly, if you’re curious, I want to show you how to find the generated binding classes and what they look like.
As you can see in this screenshot, you should be able to find all your generated Binding classes in your module’s build/generated/data_binding_base_class_source_out/debug/out/<your_package_name>/databinding
These generated files naturally won’t exist in a new project or a cleaned project, but will be there after you make or build the project.
And this is what the generated ProfileBinding class looks like. What your binding class looks like exactly is going to depend on the xml layout. In my sample project, profile.xml is just a tiny file with only a root ConstraintLayout and a single TextView.