3

I am trying to use ViewBinding in Fragments.

First, Google said as below :

Note: Fragments outlive their views. Make sure you clean up any references to the binding class instance in the fragment's onDestroyView() method. [Use view binding in fragments]

So, I have wrote the code as below :

private var _binding: ResultProfileBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

Then, I got a concern about NPE after onDestoryView().

It is safe? Suppose you received a network response at some point between onDestoryView() and onDetact()

4

1 回答 1

9

Fragments outlive their views

Let's explain it, assume you have Fragment A and B (both A and B in BackStack) same container view and same FragmentManager. When you replace fragment A by B. All view elements of A will be destroyed but the instance of Fragment A still alive in fragment BackStack. It means if you keep value of _binding it can be leaks because it still keep view reference but Android System wants to clear it. So Google recommends you assign null to _binding to release view reference.

Suppose you received a network response at some point between onDestoryView() and onDetact()

You shouldn't handle any network response after onDestroyView if it update your UI because your fragment views not present to User.

于 2020-05-27T09:08:07.977 回答