gpt4 book ai didi

android - onActivityCreated 已弃用,如何正确使用 LifecycleObserver?

转载 作者:行者123 更新时间:2023-12-03 13:25:02 37 4
gpt4 key购买 nike

Google 在 Android 上弃用 Fragment 的 onActivityCreated() 并推荐使用 LifeCycleObserver:

 To get a callback specifically when a Fragment activity's
* {@link Activity#onCreate(Bundle)} is called, register a
* {@link androidx.lifecycle.LifecycleObserver} on the Activity's
* {@link Lifecycle} in {@link #onAttach(Context)}, removing it when it receives the
* {@link Lifecycle.State#CREATED} callback.

所以我尝试以推荐的方式制作它,但我只能在 Logcat 中观察到的状态只是 状态:初始化 .
 private lateinit var lifecycleObserver: LifecycleObserver

override fun onAttach(context: Context) {
super.onAttach(context)

hostActivity = context as HostActivity

lifecycleObserver = object : LifecycleObserver {

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
Logger.tag("SOME-TAG")d("State: ${lifecycle.currentState}")

if(lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED)) {
Logger.tag("SOME-TAG").d("CREATED")
hostActivity.lifecycle.removeObserver(lifecycleObserver)
}
}
}

hostActivity.lifecycle.addObserver(lifecycleObserver)
}

上面的代码有什么问题?

更新 1 :看起来我忘了使用 hostActivity.lifecycle.currentState 并检查了 fragment 的生命周期而不是 Activity 生命周期。

更新 2 : 谷歌建议的方法不适用
当您从一个到另一个单击后退按钮时,1 个主机 Activity 和 2 个 fragment ,导致 onAttach 从未被调用,但 onActivityCreated 被调用。

最佳答案

根据更新日志 here

The onActivityCreated() method is now deprecated. Code touching thefragment's view should be done in onViewCreated() (which is calledimmediately before onActivityCreated()) and other initialization codeshould be in onCreate(). To receive a callback specifically when theactivity's onCreate() is complete, a LifeCycleObserver should beregistered on the activity's Lifecycle in onAttach(), and removed oncethe onCreate() callback is received.


你可以在你的 fragment 类中做这样的事情:
class MyFragment : Fragment(), LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreated() {
// ... Your Logic goes here ...
}

override fun onAttach(context: Context) {
super.onAttach(context)
activity?.lifecycle?.addObserver(this)
}

override fun onDetach() {
activity?.lifecycle?.removeObserver(this)
super.onDetach()
}
}

关于android - onActivityCreated 已弃用,如何正确使用 LifecycleObserver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61306719/

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