I've been reading https://developer.android.com/topic/libraries/view-binding and was thinking about how they define their view binding property in a fragment.
This is the sample code:
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
}
So _binding
is a nullable because the reference to the view will be destroyed in onDestroyView()
. However, they use binding
as a backing property, which retrieves _binding
and makes it non-nullable (whatever the equivalent to force unwrapping is called in Kotlin).
The question is why should we have _binding
and binding
and which one should be used? It feels like if you are trying to make _binding
nullable, then why make it essentially non-nullable with binding
and risk accessing the view when it's destroyed?