3

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?

James Bond
  • 2,229
  • 1
  • 15
  • 26

1 Answers1

2

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.

Joffrey
  • 32,348
  • 6
  • 68
  • 100
  • 2
    Or you can just use a nullable one, and then make the first line of any code that uses the variable binding?.let { //rest of code here } All a matter of preferred style rather than one being right and one wrong. I prefer working with the nullable one, with the one in the OP's question you get an NPE when other threads call to UI code after onDestroy is called – Gabe Sechan Dec 15 '21 at 17:31
  • But why do we need `"reset" the binding back to null`? – James Bond Dec 16 '21 at 12:33
  • @JamesBond I'm not knowledgeable enough about android to say for sure, but I think the idea is that a single fragment instance can be attached to several views during its lifetime, so when a view is destroyed it makes sense to no longer hold a reference to it while waiting for the next one to be created – Joffrey Dec 16 '21 at 16:20