Based on official documentation when we use ViewBinding in fragments, we should set binding to null in onDestroyView
of the fragment:
private var _binding:MainFragmentBinding?=null
private val binding get()=_binding!!
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
What about custom views? Do we need to set binding to null in onDetachFromWindow
or any other function?
No. It is fine to just have it in val
.
The issue with fragments is that Fragment and its view have different lifecycles, so holding onto the binding in fragment between onDestroyView()
and onDestroy()
uses unnecessary memory.
In custom views, it has same lifecycle as any binding stored in a class property.