gpt4 book ai didi

android - : Can't access the Fragment View's LifecycleOwner when getView() is null i. 即,在 onCreateView() 之前或 onDestroyView() 之后

转载 作者:行者123 更新时间:2023-11-29 02:18:12 35 4
gpt4 key购买 nike

我在我的应用程序中使用实时数据进行所有网络调用和响应处理。

在其中一种情况下,我的回收者 View 正在其 View 持有者的 onBind 中加载一些数据,并且响应正在更新 UI。为此,我必须向观察者提供一个 lifecycleOwner

由于回收器 View 没有自己的任何生命周期所有者,因此我通过 parentFragment.viewlifecycleOwner 使用父 fragment ,但不知何故它给出了一个错误。

当父 fragment 没有实例时, View 持有者如何拥有实例?

viewModel.responseState.observe(parentFragment.viewLifecycleOwner, Observer {
updateUI(it)
})

Fatal Exception: java.lang.IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()

最佳答案

这可以通过触发引发错误的逻辑来解决,从 onCreateView(...) 回调(不是 onCreate(...) 也不是 onAttach(...)).

getViewLifecycleOwner( ) 文档,我不认为,我可以更好地解释:

The first method where it is safe to access the view lifecycle is onCreateView(LayoutInflater, ViewGroup, Bundle) under the condition that you must return a non-null view (an IllegalStateException will be thrown if you access the view lifecycle but don't return a non-null view).

The view lifecycle remains valid through the call to onDestroyView(), after which getView() will return null, the view lifecycle will be destroyed, and this method will throw an IllegalStateException. Consider using getViewLifecycleOwnerLiveData() or FragmentTransaction.runOnCommit(Runnable) to receive a callback for when the Fragment's view lifecycle is available.

public LifecycleOwner getViewLifecycleOwner() {
if (mViewLifecycleOwner == null) {
throw new IllegalStateException("Can't access the Fragment View's LifecycleOwner when "
+ "getView() is null i.e., before onCreateView() or after onDestroyView()");
}
return mViewLifecycleOwner;
}

关于android - : Can't access the Fragment View's LifecycleOwner when getView() is null i. 即,在 onCreateView() 之前或 onDestroyView() 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58743684/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com