gpt4 book ai didi

android - 如何获取LifecycleObserver中的LifecycleOwner?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:55:45 25 4
gpt4 key购买 nike

我需要在 LifecycleObserver 中获取 LifecycleOwner 以将其传递给 ViewModel 观察器。

这是我的 MainActivity,我添加了 LifecycleObserver。

public class MainActivity extends AppCompatActivity implements LifecycleOwner{

private LifecycleRegistry mLifecycleRegistry;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, MainFragment.newInstance())
.commitNow();
}

mLifecycleRegistry=new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
getLifecycle().addObserver(new MyLifecycleObserver());
}


@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}

}

这是我的观察者,我需要 LifecycleOwner。

public class MyLifecycleObserver implements LifecycleObserver {


@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStartListener(){

FirebaseMassage.startFirebase();

MainFragment.massageViewModel.getMassage().observe(/*here I need the LifecycleOwner*/, textMassage -> {
FirebaseMassage.updateFirebaseMassage(textMassage);
});

}
}

最佳答案

您可以使用另一个签名来获取 LifecycleOwner,例如:

public class MyLifecycleObserver implements LifecycleObserver {


@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStartListener(LifecycleOwner owner){
...
}
}

关于android - 如何获取LifecycleObserver中的LifecycleOwner?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51973851/

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