|
|
@@ -0,0 +1,72 @@
|
|
|
+package com.atmob.keyboard_android.component.widget.lifecycle
|
|
|
+
|
|
|
+import android.content.Context
|
|
|
+import android.util.AttributeSet
|
|
|
+import android.view.View
|
|
|
+import android.widget.FrameLayout
|
|
|
+import androidx.lifecycle.Lifecycle
|
|
|
+import androidx.lifecycle.LifecycleOwner
|
|
|
+import androidx.lifecycle.LifecycleRegistry
|
|
|
+
|
|
|
+/**
|
|
|
+ * 普通的ViewGroup,不支持Jetpack的Lifecycle组件,该类进行自定义支持
|
|
|
+ */
|
|
|
+open class LifecycleViewGroup @JvmOverloads constructor(
|
|
|
+ context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
|
|
|
+) : FrameLayout(context, attrs, defStyleAttr), LifecycleOwner {
|
|
|
+ private val lifecycleRegistry = LifecycleRegistry(this)
|
|
|
+
|
|
|
+ override val lifecycle: Lifecycle
|
|
|
+ get() = lifecycleRegistry
|
|
|
+
|
|
|
+ init {
|
|
|
+ // 初始化状态
|
|
|
+ lifecycleRegistry.currentState = Lifecycle.State.INITIALIZED
|
|
|
+ lifecycleRegistry.currentState = Lifecycle.State.CREATED
|
|
|
+ }
|
|
|
+
|
|
|
+ override fun onAttachedToWindow() {
|
|
|
+ super.onAttachedToWindow()
|
|
|
+ // View添加到View树中,变更状态为可见
|
|
|
+ lifecycleRegistry.currentState = Lifecycle.State.STARTED
|
|
|
+ updateStateOnVisibility()
|
|
|
+ }
|
|
|
+
|
|
|
+ override fun onDetachedFromWindow() {
|
|
|
+ // View从View树中移除,变更状态为销毁
|
|
|
+ lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
|
|
|
+ super.onDetachedFromWindow()
|
|
|
+ }
|
|
|
+
|
|
|
+ override fun onVisibilityChanged(changedView: View, visibility: Int) {
|
|
|
+ super.onVisibilityChanged(changedView, visibility)
|
|
|
+ // 监听可见性变化,变更状态
|
|
|
+ updateStateOnVisibility()
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 可见性变化,变更状态
|
|
|
+ */
|
|
|
+ private fun updateStateOnVisibility() {
|
|
|
+ when (visibility) {
|
|
|
+ VISIBLE -> {
|
|
|
+ if (lifecycleRegistry.currentState.isAtLeast(Lifecycle.State.STARTED)) {
|
|
|
+ lifecycleRegistry.currentState = Lifecycle.State.RESUMED
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ INVISIBLE, GONE -> {
|
|
|
+ if (lifecycleRegistry.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
|
|
|
+ lifecycleRegistry.currentState = Lifecycle.State.STARTED
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 获取LifecycleOwner
|
|
|
+ */
|
|
|
+ fun getLifecycleOwner(): LifecycleOwner {
|
|
|
+ return this
|
|
|
+ }
|
|
|
+}
|