7

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
SmallGrammer
  • 893
  • 9
  • 19

2 Answers2

6

_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.

mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
4

The reason behind this is to make code easier to read and maintain when you know for sure that you won't try to access the view before onCreateView and after onDestroyView. The non-null property avoids the unnecessary ? or !! null safety operators every time you're trying to reach the binding.

On the other hand if you're uncertain about your call sequences and may try to access the fragment view when the view is destroyed, you wouldn't need to take that extra step and put your binding instance in a backing property. The null safety is your dearest friend in this case.

Sdghasemi
  • 5,370
  • 1
  • 34
  • 42