binding breaks after screen rotation

Viewed 37

I have exception "lateinit property binding has not been initialized" after screen rotation when I try call binding . How I can fix it ?

My base fragment code

    override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?,
): View? {
    binding = DataBindingUtil.inflate(inflater, contentLayoutID, container, false)
    return binding.root
}
1 Answers

Instead of initializing binding using lateinit binding, you should initialize it like that:

private var _binding: TypeOfBindingHere? = null
private val binding get() = _binding!!

And now your onCreateView should look like this:

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?,
): View? {
    _binding = DataBindingUtil.inflate(inflater, contentLayoutID, container, false)
    return binding.root
}
Related