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?
_binding
is nullable
so that it can be set to null in onDestroyView
, avoiding any memory leaks. but if you tried to access views using _binding
then you will have to write _binding!!.someView
every time you access any view, use of non-null assertion(!!
) quickly becomes redundant and verbose.
So to remove this redundancy there is non-nullable binding
. Now you can access your views as binding.someView
, no need to use non-null assertion (!!). This can not cause any issue, since views should only be accessed between onCreateView
and onDestroyView
.