关于LifecycleEventObserver
Lifecycle可以添加观察者,从而让其它工作与周期变化保持一致
比如我们希望Dialog和Activity的生命周期一致,能够在Activity结束时自动关闭
可以通过如下代码来实现
与Lifecycle同步的Dialog
kotlin
package com.android.code
import android.app.Dialog
import androidx.activity.ComponentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
class LifecycleDialog(
private val activity: ComponentActivity
) : Dialog(activity), LifecycleEventObserver {
init {
activity.lifecycle.addObserver(this)
}
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (event == Lifecycle.Event.ON_DESTROY && isShowing) dismiss()
}
}