Published in


ViewBinding in Fragments: the clean & easy way

When using ViewBinding (available from Android Studio 3.6), a best practice is to nullify the binding in a Fragment’sonDestroyView. In our project, we often forgot to do so. We also copy-pasted binding logic to all our Fragments, causing duplicate code, and added an abundant number of null checks in our Fragments’ methods. To clean up our code we created a ViewBindingHolder class that takes care of the binding’s lifecycle and supplies some helper methods that keep the code in our fragments safe and short.

The advantage of this approach

  • enables safe access to the binding property.
  • makes code short and clean.
  • nullifies the binding at the end of the lifecycle.


Using the ViewBindingHolder requires two adjustments to the Fragment:

  1. ViewBindingHolder<YourBindingClass> by… to initialize the ViewBindingHolder class as a delegate to your Fragment.
  2. initBinding in onCreateView to bind the view.

Outside of onCreateView, there are two ways to access the binding:

1. binding?

Assuming that the binding might be null is the safest option. Since we’re using a delegate you can access the binding property directly from your Fragment.

binding?.textTitle.text = “The safest way to access”

2. requireBinding()

When you are sure your logic runs within the view lifecycle of the fragment, you can use requireBinding().

fun initTitle() = requireBinding() {
// here, 'this' is the 'binding' property.
textTitle.text = "ViewBinding and Lifecycle handling"

You can also use it without a code block:

fun initTitle() {
val binding = requireBinding()
binding.textTitle.text = "ViewBinding and Lifecycle handling"

When requireBinding() is called outside of the Fragment’s view lifecycle, it will throw an IllegalStateException, similar to the behaviour of requireActivity().

Inside ViewBindingHolder

This is the class that makes it possible, I added some comments to explain the details.

To use it, copy the ViewBindingHolder class to some central place inside your project. Let me know if you find any room for improvement!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store