Ale*_*KTP 4 android android-lifecycle fragment-lifecycle
我需要让 LifecycleOwner 在我的 FirestoreRecyclerViewOption 中传递它,但 Fragment 没有实现 Lifecycle。
那么,如何获得呢?
我的 Fragment 实现 LifecycleOnwer,如下面的代码示例所示,
public class ListRestFragment extends Fragment implements LifecycleOwner
Run Code Online (Sandbox Code Playgroud)
在 onCreateMethod 之后,
lifecycleRegistry = new LifecycleRegistry(this);
lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
Run Code Online (Sandbox Code Playgroud)
并完成
@Override
public void onStart() {
super.onStart();
lifecycleRegistry.setCurrentState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}
Run Code Online (Sandbox Code Playgroud)
我按照这个例子,但它不起作用
Attempt to invoke virtual method 'androidx.lifecycle.Lifecycle$State androidx.lifecycle.Lifecycle.getCurrentState()' on a null object reference
Run Code Online (Sandbox Code Playgroud)
我需要它来编辑 My FirestoreRecyclerViewOption 和 setLifeCycleOwner 因为它始终为 null 并且我每次都有一个 NullPointer 。
更新:实际上,如果您在观察者中使用视图,最好使用getViewLifeCycleOwner。因为当 LiveData 更新时视图可能不存在并且您想要更改导致崩溃的视图(例如更改视图的可见性)。
片段本身就是您正在寻找的 LifecycleOwner。您可以使用关键字“this”作为对片段的引用。
阅读:“生命周期 是一个类,它保存有关组件(如活动或片段)生命周期状态的信息,并允许其他对象观察此状态。”
并且:“LifecycleOwner 是一个单一的方法接口,表示该类具有生命周期。”
| 归档时间: |
|
| 查看次数: |
7059 次 |
| 最近记录: |