Why is it important to clear the binding
in onDestroyView
when implementing Android View Binding in a Fragment?
As the documentation shows, Use view binding in fragments, and the Android Architecture Components sample, the binding
is initiated in onCreateView
, and cleared in onDestroyView
.
What is the benefit of implementing this compared to initiating the binding
without clearing it in onDestroyView
? Without explicitly clearing the instance variable binding
, it should be cleared when the Fragment is destroyed.
private var _binding: ResultProfileBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = ResultProfileBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
ViewBinding vs DataBindingThe main advantages of viewbinding are speed and efficiency. It has a shorter build time because it avoids the overhead and performance issues associated with DataBinding due to annotation processors affecting DataBinding's build time.
Conversely, view binding has the following limitations compared to data binding: View binding doesn't support layout variables or layout expressions, so it can't be used to declare dynamic UI content straight from XML layout files. View binding doesn't support two-way data binding.
View binding allows a developer to incorporate significant interaction in an application. This concept seeks to eliminate the findViewById keyword. Removing such boilerplate code allows developers to be more productive. A binding class is usually generated for each layout file when using view binding.
A Fragment can potentially have its view created and destroyed multiple times while the Fragment instance itself is still in memory. If you don't null out the view references, you are "leaking" these views during the span of time between onDestroyView()
and onCreateView()
. They aren't permanently leaked though, so perhaps that is the wrong term.
There are some who say it doesn't matter if these views are temporarily leaked. I don't know the lifecycle details enough to know if it strictly matters. I would expect that sometimes the reason views are torn down is that Android is trying to save memory while they are off screen, so if you hang onto them, you are subverting that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With