ViewBinding is a huge improvement over findViewById, but if you're not careful within a
Fragment, you're creating memory leaks and potentially triggering NullPointerExceptions.
The Lifecycle Trap
Unlike Activities, a Fragment's view can be destroyed while the Fragment instance itself stays alive. This happens during configuration changes or when the Fragment goes into the backstack.
// This will leak or crash if called after onDestroyView
binding.recyclerView.adapter = myAdapter
The Recommended Pattern
To safely use ViewBinding in Fragments, you must null out the reference in
onDestroyView. I use a backing property to make the code cleaner throughout the
Fragment.
private var _binding: MyFragmentBinding? = null
private val binding get() = _binding!!
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
Summary
Always null out your Fragment bindings. It's an extra 3 lines of code but it prevents hundreds of potential crashes in production. Memory management is key!