【问题标题】:CustomView lifecycle onDetachedFromWindow() not fired未触发 CustomView 生命周期 onDetachedFromWindow()
【发布时间】:2019-08-23 11:01:11
【问题描述】:

我正在使用 ValueAnimator 为自定义视图设置动画,并使用下面的代码在视图与屏幕分离时停止动画器。但我意识到,当应用程序被最近(概述)或主页按钮从窗口管理器中删除时,onDetachedFromWindow() 不会被调用:

我取消 ValueAnimator 的方式:

override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        mSqueezebarAnimator?.start()
    }

    override fun onDetachedFromWindow() {
        mSqueezebarAnimator?.cancel()
        super.onDetachedFromWindow()
    }

我现在做什么:

override fun onWindowVisibilityChanged(visibility: Int) {
        super.onWindowVisibilityChanged(visibility)

        mSqueezebarAnimator?.let {
            if (it.isStarted && visibility in setOf(View.INVISIBLE, View.GONE)){
                it.cancel()
            }else if (it.isStarted.not()) {
                it.start()
            }
        }
    }

我刚刚删除了onAttachedToWindow/onDetachedFromWindow 并添加了onWindowVisibilityChanged。我想知道这个解决方案的缺点,我的意思是可能出现什么问题?

请注意,我不想通过 Activity 生命周期方法控制视图

【问题讨论】:

    标签: android android-view android-custom-view


    【解决方案1】:

    如果您查看与您的场景相似的组件的源代码,例如 ProgressBar,您会看到在两个回调 onVisibilityAggregatedonDetachedFromWindow 中动画都停止了。在我看来,这对您的情况也不构成问题。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-28
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多