如何在片段中获取生命周期所有者?



我需要让生命周期所有者在我的FirestoreRecyclerViewOption中传递它,但Fragment没有实现生命周期。

那么,如何获得呢?

我的片段实现了生命周期,如下面的代码示例所示,

public class ListRestFragment extends Fragment implements LifecycleOwner 

在onCreateMethod之后,

lifecycleRegistry = new LifecycleRegistry(this);
lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);

并完成

@Override
public void onStart() {
super.onStart();
lifecycleRegistry.setCurrentState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}

我遵循这个例子 但它不起作用

Attempt to invoke virtual method 'androidx.lifecycle.Lifecycle$State androidx.lifecycle.Lifecycle.getCurrentState()' on a null object reference

我需要它来编辑My FirestoreRecyclerViewOption并设置LifeCycleOwner,因为它总是为空,并且我每次都有一个NullPointer 。

在片段中,您可以使用getViewLifecycleOwner()方法来获取生命周期所有者。

更新:实际上,如果您在观察器中使用视图,最好使用 getViewLifeCycleOwner。因为当 LiveData 更新时视图可能不存在,并且您想要更改视图(例如更改视图的可见性(,这会导致崩溃。

片段本身就是您要查找的生命周期所有者。您可以使用关键字"this"作为对片段的引用。

阅读以下内容:"生命周期 是一个类,它保存有关组件(如活动或片段(的生命周期状态的信息,并允许其他对象观察此状态。

和: "生命周期所有者是一个单一方法接口,表示类具有生命周期。

最新更新