Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android View Binding - Clear Binding in Fragment Lifecycle

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
}
like image 608
Adam Hurwitz Avatar asked Dec 14 '20 19:12

Adam Hurwitz


People also ask

Which is better view binding or data binding in Android?

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.

Can I use both data binding and view binding?

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.

What is view binding in Android?

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.


1 Answers

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.

like image 148
Tenfour04 Avatar answered Oct 29 '22 21:10

Tenfour04