Android View Binding – Clear Binding in Fragment Lifecycle

Issue

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
}

Solution

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.

Answered By – Tenfour04

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published