如何在对话框中使用 Android LifecycleOwner

How to use Android LifecycleOwner in dialog

我想在Dialog中使用mvvm但不知道如何通过LifecycleOwner观察

class CommonDialog(context: Context) : Dialog(context, R.style.AppMaskStatusTheme) {

    private val viewBinding: DialogSportOrderBinding by lazy { DialogSportOrderBinding.inflate(LayoutInflater.from(context)) }
    private val viewModel by lazy { ViewModelProvider(context as ViewModelStoreOwner)[SportOrderViewModel::class.java] }

 init {
        setContentView(viewBinding.root)

        viewModel.sportOrderList.observe(***what to pass here?***, androidx.lifecycle.Observer {

        })
    }
}

我试过context as LifecycleOwnercontext as AppCompatActivity但都失败了

请帮助我,谢谢!

android.content.Context 没有实现 android.arch.lifecycle.LifecycleOwner.

您必须传递一个 AppCompatActivity 的实例,它实现了 android.arch.lifecycle.LifecycleOwner(或任何其他实现该功能的 class)。

或转换 (AppCompatActivity) context,当 contextinstanceof AppCompatActivity.

您可以像这样创建自己的 LifecycleOwner

class MyLifecycleOwner() : LifecycleOwner {
    private val mLifecycleRegistry: LifecycleRegistry by lazy { LifecycleRegistry(this) }

    init {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
    }

    fun stop() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
    }

    fun start() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
    }

    override fun getLifecycle(): Lifecycle = mLifecycleRegistry
}

那么你的Dialogclass会是这样

class CommonDialog(context: Context) : Dialog(context, R.style.AppMaskStatusTheme) {

    private val viewBinding: DialogSportOrderBinding by lazy { DialogSportOrderBinding.inflate(LayoutInflater.from(context)) }
    private val viewModel by lazy { ViewModelProvider(context as ViewModelStoreOwner)[SportOrderViewModel::class.java] }

    private val lifeCycleOwner: MyLifecycleOwner by lazy { MyLifecycleOwner() }

    init {
        setContentView(viewBinding.root)

        viewModel.sportOrderList.observe(lifeCycleOwner, {

        })
    }

    override fun onStart() {
        super.onStart()
        lifeCycleOwner.start()
    }

    override fun onStop() {
        super.onStop()
        lifeCycleOwner.stop()
    }
}

阅读更多关于 Lifecycle-Aware Components at here