|
|
@@ -7,24 +7,29 @@ import android.widget.FrameLayout
|
|
|
import androidx.lifecycle.Lifecycle
|
|
|
import androidx.lifecycle.LifecycleOwner
|
|
|
import androidx.lifecycle.LifecycleRegistry
|
|
|
+import androidx.lifecycle.ViewModelStore
|
|
|
+import androidx.lifecycle.ViewModelStoreOwner
|
|
|
|
|
|
/**
|
|
|
- * 普通的ViewGroup,不支持Jetpack的Lifecycle组件,该类进行自定义支持
|
|
|
+ * 普通的ViewGroup,不支持Jetpack的Lifecycle组件和ViewModel组件,该类进行自定义支持
|
|
|
*/
|
|
|
open class LifecycleViewGroup @JvmOverloads constructor(
|
|
|
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
|
|
|
-) : FrameLayout(context, attrs, defStyleAttr), LifecycleOwner {
|
|
|
- private val lifecycleRegistry = LifecycleRegistry(this)
|
|
|
+) : FrameLayout(context, attrs, defStyleAttr), LifecycleOwner, ViewModelStoreOwner {
|
|
|
+ // 实现ViewModelStore组件
|
|
|
+ override val viewModelStore by lazy {
|
|
|
+ ViewModelStore()
|
|
|
+ }
|
|
|
+
|
|
|
+ // 实现Lifecycle组件
|
|
|
+ private val lifecycleRegistry = LifecycleRegistry(this).apply {
|
|
|
+ currentState = Lifecycle.State.INITIALIZED
|
|
|
+ currentState = Lifecycle.State.CREATED
|
|
|
+ }
|
|
|
|
|
|
override val lifecycle: Lifecycle
|
|
|
get() = lifecycleRegistry
|
|
|
|
|
|
- init {
|
|
|
- // 初始化状态
|
|
|
- lifecycleRegistry.currentState = Lifecycle.State.INITIALIZED
|
|
|
- lifecycleRegistry.currentState = Lifecycle.State.CREATED
|
|
|
- }
|
|
|
-
|
|
|
override fun onAttachedToWindow() {
|
|
|
super.onAttachedToWindow()
|
|
|
// View添加到View树中,变更状态为可见
|
|
|
@@ -35,13 +40,17 @@ open class LifecycleViewGroup @JvmOverloads constructor(
|
|
|
override fun onDetachedFromWindow() {
|
|
|
// View从View树中移除,变更状态为销毁
|
|
|
lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
|
|
|
+ // 清理ViewModel
|
|
|
+ viewModelStore.clear()
|
|
|
super.onDetachedFromWindow()
|
|
|
}
|
|
|
|
|
|
override fun onVisibilityChanged(changedView: View, visibility: Int) {
|
|
|
super.onVisibilityChanged(changedView, visibility)
|
|
|
// 监听可见性变化,变更状态
|
|
|
- updateStateOnVisibility()
|
|
|
+ if (changedView == this) {
|
|
|
+ updateStateOnVisibility()
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -50,13 +59,13 @@ open class LifecycleViewGroup @JvmOverloads constructor(
|
|
|
private fun updateStateOnVisibility() {
|
|
|
when (visibility) {
|
|
|
VISIBLE -> {
|
|
|
- if (lifecycleRegistry.currentState.isAtLeast(Lifecycle.State.STARTED)) {
|
|
|
+ if (lifecycleRegistry.currentState == Lifecycle.State.STARTED) {
|
|
|
lifecycleRegistry.currentState = Lifecycle.State.RESUMED
|
|
|
}
|
|
|
}
|
|
|
|
|
|
INVISIBLE, GONE -> {
|
|
|
- if (lifecycleRegistry.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
|
|
|
+ if (lifecycleRegistry.currentState == Lifecycle.State.RESUMED) {
|
|
|
lifecycleRegistry.currentState = Lifecycle.State.STARTED
|
|
|
}
|
|
|
}
|