0

I now need to keep the status when I return, so I write as follows:

@AndroidEntryPoint
class IndexFragment : Fragment() {
    private var rootView: View? = null
    private var isFirstLoad = true
    
    override fun onCreateView(
       inflater: LayoutInflater, container: ViewGroup?,
       savedInstanceState: Bundle?,
    ): View? {
        if (isFirstLoad) {
            initView()
        }
        return rootView
   }
   private fun initView() {
       binding = FragmentIndexBinding.inflate(layoutInflater)
       rootView = binding?.root
   }
}

I'm a novice android. Leakcanary will report the rootView memory leak problem.I don't know whether this is a false alarm of Leakcanary or a real memory leak. I added a shared element transition and a page in a nested fragment. In addition, I can't think of how to keep the state when the previous page returns.

史新雨
  • 1
  • 1

1 Answers1

0

If you take a look at the documentation viewBinding in fragments should look like:

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 // <-- this prevents memory leaks! (and I think that's the problem in your case)
}

edit: You might be confused why we are nullifying the _binding variable in onDestroyView, so here's the explanation:

The fragment outlives the view, which means that if we forget to clear the binding reference in onDestroyView this will cause a memory leak.

JustSightseeing
  • 1,460
  • 3
  • 17
  • 37