如何在自定义视图中观察 LiveData

How to observe LiveData inside Custom View

我应该如何在自定义视图中观察 LiveData。我试图将它的上下文转换为 lifecycleOwner 但它会产生一些问题并且在所有情况下都不起作用。 我试着放一个 setter 但它也不起作用

视图本身没有生命周期。有两种个人使用的方法,它们实际上是同一件事,但其中一种是添加生命周期,而另一种是。没有生命周期。

class MyCustomView  @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
): View(context, attrs, defStyleAttr){
    
    
    val myObserver = Observer<Long>{
        //whatever
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        liveData.observeForever(myObserver)
    }

    override fun onDetachFromWindow() {
        super.onDetachFromWindow()
        liveData.removeObserver(myObserver)
    }
}

此方法在 attach/detach 到 window 上手动 observe/remove。当我观察很少的实时数据时我更喜欢它,它是 simple/limited


另一种选择是将我们的自定义视图变成 LifecycleOwner。我推荐这种方法 BaseCustomViews 和一些非常庞大和复杂的视图(如地图导航视图)

class BaseCustomView  @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
): View(context, attrs, defStyleAttr), LifecycleOwner {
    protected val lifecycleRegistry = LifecycleRegistry(this);

    override fun getLifecycle() = lifecycleRegistry
    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        lifecycleRegistry.currentState = Lifecycle.State.RESUMED
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
    }


    
    val myObserver = Observer<Long>{
        //whatever
    }

    init{
        liveData.observe(this, myObserver}
    }
}