In android documentation we have example of view binding without lateinit:
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
}
Why we are not using lateinit, like we use it in activity:
private lateinit var binding: ResultProfileBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = ResultProfileBinding.inflate(inflater, container, false)
return binding.root
}
I suspect it has something with a memory leak problem. Can you explain it?
I found a good explanation here.
Snippet from the explanation:
How do leaks happen in fragments? First, we need to start by reviewing the important nuance of fragments. They have two different lifecycles:
- It’s own lifecycle (
onCreateandonDestroy)- It’s view’s lifecycle (
onCreateViewandonDestroyView)Having two lifecycles for a single screen can be problematic. They are created and destroyed at different times, for instance, when putting a fragment on the back-stack. Specifically, holding onto views after
onDestroyViewis called will leak. This happens when a fragment is on the back stack, and although its view is destroyed, the fragment itself is not. The garbage collector is unable to clear the reference to those views.
And one snippet from this Stack Overflow answer:
You have to null out your references to the views in
onDestroyViewas that's the sign that the view is no longer being used by the Fragment system and it can be safely garbage collected if it wasn't for your continued reference to theView.
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