【问题标题】:ValueAnimator Lint Error: This animation should be started with #start() [Recycle]ValueAnimator Lint 错误:此动画应以 #start() [Recycle] 开始
【发布时间】:2021-08-03 11:56:20
【问题描述】:

我在 init() 方法中创建 ValueAnimator,如下所示:

internal var animator: ValueAnimator? = null

@CallSuper
open fun init() {
    animator = ValueAnimator.ofFloat(-1F, 2F)
    animator?.duration = ANIMATION_DURATION
    animator?.interpolator = LinearInterpolator()
    animator?.repeatCount = ValueAnimator.INFINITE
    animator?.repeatMode = ValueAnimator.REVERSE
    animator?.addUpdateListener(this)
}

我根据视图的可见性开始/停止它:

override fun onVisibilityChanged(changedView: View, visibility: Int) {
    super.onVisibilityChanged(changedView, visibility)
    when (visibility) {
        VISIBLE -> animator?.start()
        INVISIBLE, GONE -> animator?.cancel()
    }
}

我收到以下 Lint 错误:

错误:此动画应以#start() [Recycle] 开始 动画师 = ValueAnimator.ofFloat(-1F, 2F) ~~~~~~~

“回收”类型问题的说明:许多资源,例如 作为 TypedArrays、VelocityTrackers 等,应该被回收(带有 recycle() 调用)使用后。此 lint 检查查找丢失 recycle() 调用。

ValueAnimator 没有 recycle() 方法。每次我需要启动它时,我都尝试创建一个新的动画师,但我找不到提供所需属性的方法,而不会出现此 Lint 错误。我该如何解决这个问题?

【问题讨论】:

  • 让我猜猜,当您的视图在可见之前就消失/不可见时,您可能会遇到此问题。这意味着如果它没有运行,你就不能取消()动画。可见性也是如此。动画应该是可重入且一致的。我建议您阅读这篇文章一次:medium.com/androiddevelopers/…
  • 感谢您的文章。运行应用程序时动画没有任何问题,它工作得很好。问题在于 Lint 给出了这个错误,我不知道如何修复它 - 在这种情况下如何正确回收 animator。

标签: android kotlin lint animator


【解决方案1】:

为了避免 lint 错误,您可以在每次视图可见时创建一个值动画器实例,如下所示:-

fun createAndStartAnim() {
     animator = ValueAnimator.ofFloat(-1F, 2F).apply {
             duration = ANIMATION_DURATION
             interpolator = LinearInterpolator()
             repeatCount = ValueAnimator.INFINITE
             repeatMode = ValueAnimator.REVERSE
             addUpdateListener(this@YourUpdateListener)
             start() // this removes the lint error
     }
}

我们需要取消:-

fun cancelAndNullifyAnim() {
    animator?.cancel()
    animator = null
}

现在可见度变化:-

when (visibility) {
        VISIBLE -> createAndStartAnim()
        INVISIBLE, GONE -> cancelAndNullifyAnim()
}

如果我们在访问它的任何其他可回收属性之前启动 value anim,则 lint 错误应该消失。

【讨论】:

    猜你喜欢
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多