Search code examples
androidkotlinandroid-viewbinding

Why do we need 2 "binding" variables when working with ViewBinding in Android?


Let's look at the official example:

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 are there 2 similar variables: _binding and binding? Why can't we use one variable?


Solution

  • This is to have a non-nullable view of the binding property for convenience in the rest of the code, but still have the possibility to manage the actual nullable value in onCreateView/onDestroyView via _binding.

    The lateinit approach in activities is nicer, but with lateinit you can't "reset" the binding back to null, so it's not applicable for fragments.