I was going through developer docs for Data binding. I found the following snippet:
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
}
Can anyone let me know the principle and advantage of using two variables for binding which are used in same fragment?
At first glance, it seems like lateinit
would be a more natural choice. However, the Fragment instance is still usable after onDestroyView
since Fragment instances can be torn down and reattached later. lateinit
won't let you change the parameter back into uninitialized state, so it's not suitable for this purpose.
Using !!
can result in Kotlin NPEs, which is not great. I would suggest modifying the sample code to provide better documentation and error reporting, like this:
/** This property is only valid between onCreateView and onDestroyView. */
private val binding get() = _binding ?:
error("Binding is only valid between onCreateView and onDestroyView.")
But practically, your Fragment is not going to be so complicated that you would have trouble tracking down an error like this anyway.