小编Ale*_*KTP的帖子

如何在 Fragment 中获取 LifecycleOwner?

我需要让 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 。

android android-lifecycle fragment-lifecycle

4
推荐指数
2
解决办法
7059
查看次数