Is there anyway to add to the instance of the viewBinding viewLifecycleOwner to prevent assigning the binding to null in the onDestroyView() of a Fragment ?
Example
class BindFragment : Fragment(R.layout.fragment_blank) {
// Scoped to the lifecycle of the fragment's view (between onCreateView and onDestroyView)
private var fragmentBlankBinding: FragmentBlankBinding? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentBlankBinding.bind(view)
fragmentBlankBinding = binding
binding.textViewFragment.text = getString(string.hello_from_vb_bindfragment)
}
override fun onDestroyView() {
// Consider not storing the binding instance in a field, if not needed.
fragmentBlankBinding = null
super.onDestroyView()
}
}
Could be transformed as
class BindFragment : Fragment(R.layout.fragment_blank) {
// Scoped to the lifecycle of the fragment's view (between onCreateView and onDestroyView)
private lateinit var fragmentBlankBinding: FragmentBlankBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentBlankBinding.bind(viewLifecycleOwner,view)
fragmentBlankBinding = binding
binding.textViewFragment.text = getString(string.hello_from_vb_bindfragment)
}
}
This way the binding could handle the destroy of the instance by itself instead of manually doing it in each Fragment that provides the bindings
It maybe can be called viewBindingLifecycleOwner and it should handle this removal of the instance by itself
Source: https://developer.android.com/topic/libraries/view-binding#fragments
See my extension functions: https://github.com/hoc081098/ViewBindingDelegate
It's not really a solution, just an alternative way to do the same thing.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
FragmentBlankBinding.bind(view).apply {
textView.text = getString(string.hello_from_vb_bindfragment)
// Set up other ui related stuff
}
}
So you avoid having to assign null to binding.
Excellent @hoc081098 , thanks
Most helpful comment
See my extension functions: https://github.com/hoc081098/ViewBindingDelegate