【问题标题】:How to get LifecycleOwner in a Fragment?如何在片段中获取 LifecycleOwner?
【发布时间】:2019-10-17 18:44:13
【问题描述】:

我需要让 LifecycleOwner 在我的 FirestoreRecyclerViewOption 中传递它,但 Fragment 没有实现 Lifecycle。

那么,如何获得呢?

My Fragment 实现 LifecycleOnwer 如下代码示例所示,

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 和 setLifeCycleOwner,因为它始终为 null,而且我每次都有一个 NullPointer。

【问题讨论】:

  • 你在使用已弃用的框架 Fragments 吗?所有支持库/AndroidX 片段都已经实现了 LifecycleOwner。
  • @ianhanniballake 我的应用是基于 Api 19 构建的。
  • 好的,那么您使用的是什么 Fragments?支持库片段支持回到 API 14
  • @ianhanniballake 我使用 androidx.fragment.app
  • 那么他们已经按照the documentation实现了LifecycleOwner。

标签: android android-lifecycle fragment-lifecycle


【解决方案1】:

在片段中你可以使用getViewLifecycleOwner() 方法来获取lifeCycleOwner。

【讨论】:

  • 这应该是答案
【解决方案2】:

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

片段本身就是您要查找的 LifecycleOwner。您可以使用关键字“this”作为对片段的引用。

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

并且: “LifecycleOwner 是一个单一的方法接口,表示该类有一个生命周期。”

【讨论】:

  • getViewLifecycleOwner() 不是“这个”
猜你喜欢
  • 1970-01-01
  • 2019-06-24
  • 2021-08-28
  • 2014-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
相关资源
最近更新 更多