android / architecture-components-samples

Samples for Android Architecture Components.
https://d.android.com/arch
Apache License 2.0
23.36k stars 8.28k forks source link

Why the document's guide and this sample is different? ViewBinding Sample #1043

Closed DJDrama closed 3 months ago

DJDrama commented 2 years ago

Question

In Android Developers guide (https://developer.android.com/topic/libraries/view-binding) we nullify binding vairable after super.onDestroyView()

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

But when we look at the viewbinding sample, the binding variable is nullified before super.onDestroyView()

override fun onDestroyView() {
        // Consider not storing the binding instance in a field, if not needed.
        fragmentBlankBinding = null
        super.onDestroyView()
    }

What is the correct way? Official developers site's guide or sample?

DJDrama commented 3 months ago
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
}

Just use like above (Sample in official docs) closing this issue