不建议使用onActivityCreated,如何正确使用LifecycleObserver? [英] onActivityCreated is deprecated, how to properly use LifecycleObserver?
问题描述
Google在Android上弃用片段的onActivityCreated(),建议使用LifeCycleObserver:
Google deprecate fragment’s onActivityCreated() on Android and recommend to use 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中观察到的状态只是状态:INITIALIZED .
So I try to make it in recommended way, but only state I can observe in Logcat is just State: INITIALIZED.
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)
}
上面的代码有什么问题?
What is wrong in code above?
更新1 :好像我忘了使用hostActivity.lifecycle.currentState并检查了片段的生命周期,而不是Activity生命周期.
UPDATE 1: Looks like I forgot to use hostActivity.lifecycle.currentState and checked fragment's lifecycle instead of Activities lifecycle.
更新2 :由Google建议的方法不适用于 1个主机活动和2个片段,当您从一个按钮单击到另一个按钮时,导致onAttach从未调用,而是onActivityCreated调用了.
UPDATE 2: Suggested by Google approach not worked for 1 Host activity and 2 fragments when you click back button from one to another, cause onAttach never called, but onActivityCreated called.
推荐答案
我是通过以下方式实现的:
I did it in next way:
class MyActivityObserver(
private val update: () -> Unit
) : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
owner.lifecycle.removeObserver(this)
update()
}
}
并在onAttach(或其他生命周期方法)片段中使用它,例如:
and use it in fragments onAttach (or another lifecycle method) like:
myActivity.lifecycle.addObserver(MyActivityObserver {
myOnActivityCreated()
})
这篇关于不建议使用onActivityCreated,如何正确使用LifecycleObserver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!