1

我想在 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但都失败了

请帮助我,谢谢!

4

2 回答 2

1

您可以像这样创建自己的 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
}

那么你的 Dialog 类将是这样的

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()
    }
}

在此处阅读有关生命周期感知组件的更多信息

于 2021-12-27T09:02:47.233 回答
0

android.content.Context不执行android.arch.lifecycle.LifecycleOwner

您必须传递 的实例AppCompatActivity,该实例实现android.arch.lifecycle.LifecycleOwner(或任何其他执行此操作的类)。

或 cast (AppCompatActivity) context, whencontextinstanceof AppCompatActivity.

于 2021-12-27T08:15:27.617 回答