在我的片段中,我使用 viewlifecycleowner 来观察实时数据,但在某些情况下,我的应用程序会因以下日志而崩溃:
Fatal Exception: java.lang.IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()
所以我问如何重现并避免这个问题!
您应该在
LiveData
的 Fragment
中注册您的 onViewCreated
观察者。其中 viewlifecycleowner
永远不可能是 null
。
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.someLiveData.observe(viewLifecycleOwner, Observer<Something> {
// Update the UI.
})
}
我使用观察(this@yourfragment)而不是观察(viewlifecycleowner)。这对我有用。