简体   繁体   中英

binding breaks after screen rotation

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
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM