美文网首页androidAndroidAndroid 知识
Android 自定义view中实现LifecycleOwner

Android 自定义view中实现LifecycleOwner

作者: 海阔sun天空 | 来源:发表于2021-12-23 11:46 被阅读0次

    前言

    Google官方提供的Activity和Fragment都默认实现了LifecycleOwner,而使用LiveData一般又都是在Activity和Fragment类中使用,因为在调用LiveData的Observer方法时需要传一个LifecycleOwner对象,而我们自定义的view中没有实现这个接口,所以在自定义view中使用LiveData往往需要传递一个Activity或者Fragment的对象才行,使用起来比较麻烦。网上找了一圈也没几个写自定义View中该如何实现自己的LifecycleOwner,本篇文章就介绍如何在自定义的view中简单的实现当前view的LifecycleOwner。

    实现

    代码很少,直接贴代码吧

    package com.android.car.aidlclient
    
    import android.content.Context
    import android.util.AttributeSet
    import android.util.Log
    import androidx.constraintlayout.widget.ConstraintLayout
    import androidx.lifecycle.Lifecycle
    import androidx.lifecycle.LifecycleOwner
    import androidx.lifecycle.LifecycleRegistry
    import androidx.lifecycle.MutableLiveData
    
    /**
     * @author 杜宗宁
     * @date 2021/12/23 11:02
     * @description TODO
     */
    class LifecycleView : ConstraintLayout, LifecycleOwner {
        constructor(context: Context) : super(context)
        constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
        constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
        constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(
            context, attrs, defStyleAttr, defStyleRes
        )
    
        private val liveData = MutableLiveData<Int>()
        private val mRegistry = LifecycleRegistry(this)
    
        override fun onFinishInflate() {
            super.onFinishInflate()
            postInt()
            liveData.observe(this, {
                Log.d("zdu__", "打印Int:$it")
            })
        }
    
        private fun postInt() {
            postDelayed({
                liveData.value = 1
                postInt()
            }, 1000)
        }
    
        override fun onAttachedToWindow() {
            super.onAttachedToWindow()
            mRegistry.currentState = Lifecycle.State.CREATED
            Log.d("zdu__", "view 创建")
        }
    
        override fun onDetachedFromWindow() {
            super.onDetachedFromWindow()
            mRegistry.currentState = Lifecycle.State.DESTROYED
            Log.d("zdu__", "view 销毁")
        }
    
        override fun onWindowVisibilityChanged(visibility: Int) {
            super.onWindowVisibilityChanged(visibility)
            if (visibility == VISIBLE) {
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
                Log.d("zdu__", "view 显示")
            }else if (visibility == GONE || visibility == INVISIBLE){
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
                Log.d("zdu__", "view 隐藏")
            }
        }
    
        override fun getLifecycle(): Lifecycle {
            return mRegistry
        }
    }
    
    

    原理很简单,实现LifecycleOwner接口,重写getLifecycle()方法,返回一个创建的LifecycleRegistry对象,然后在onAttachedToWindow()onDetachedFromWindow()分别设置当前的状态,在onWindowVisibilityChanged()中判断显示和隐藏,分别发送当前状态,就OK了。

    最终实现效果:



    订阅关系可以跟随View的生命周期,效果同Activity和Fragment使用。

    相关文章

      网友评论

        本文标题:Android 自定义view中实现LifecycleOwner

        本文链接:https://www.haomeiwen.com/subject/mmshqrtx.html