调试Android ValueAnimator

时间:2019-01-23 15:11:49

标签: android kotlin android-animation

我一直在尝试使用Kotlin扩展功能和CardView为我的ValueAnimator创建收起/展开动画。这是动画的代码(CardView扩展功能):

fun CardView.collapse() {
    val content = findViewById<RecyclerView>(R.id.rv_content)
    val arrow = findViewById<ImageView>(R.id.contents_arrow)
    val currentHeight = content.layoutParams.height

    val rvAnimator = ValueAnimator.ofInt(currentHeight, 0).apply {
        addUpdateListener{ updatedAnimation ->
            val params = content.layoutParams
            params.height = updatedAnimation.animatedValue as Int
            content.layoutParams = params
        }
        duration = 1000
    }

    val arrowAnimator = ValueAnimator.ofFloat(00f, 180f).apply {
        addUpdateListener { updatedAnimation ->
            arrow.rotation = updatedAnimation.animatedValue as Float
        }

        duration = 1000
        startDelay = 250
    }

    AnimatorSet().apply {
        playTogether(rvAnimator, arrowAnimator)
        start()
    }

}

fun CardView.expand(maxHeight: Int) {
    val content = findViewById<RecyclerView>(R.id.rv_content)
    val arrow = findViewById<ImageView>(R.id.contents_arrow)

    val rvAnimator = ValueAnimator.ofInt(0, maxHeight).apply {
        addUpdateListener{updatedAnimation ->
            val params = content.layoutParams
            params.height = updatedAnimation.animatedValue as Int
            content.layoutParams = params
        }
        duration = 1000
    }

    val arrowAnimator = ValueAnimator.ofFloat(180f, 0f).apply {
        addUpdateListener { updatedAnimation ->
            arrow.rotation = updatedAnimation.animatedValue as Float
        }

        duration = 1000
        startDelay = 250
    }

    AnimatorSet().apply {
        playTogether(rvAnimator, arrowAnimator)
        start()
    }

}

fun CardView.isCollapsed(): Boolean {
    val content = findViewById<RecyclerView>(R.id.rv_content)
    return content.layoutParams.height == 0

}

然后单击以启动动画:

override fun onBindViewHolder(holder: SectionViewHolder, position: Int) {

    holder.itemView.setOnClickListener {
        if ((it as CardView).isCollapsed()) {
            it.expand(holder.maxHeight)
        } else {
            it.collapse()
        }
    }
}

但是,我的动画似乎引起了一些非常奇怪的绘图问题。第一次单击CardView时会有一些延迟。不过,更令人担忧的是,CardView总是在动画结束后又回到展开状态:

enter image description here

当箭头指向上方时,CardView应该合拢,反之亦然。

任何人都可以就如何解决此问题提供任何意见吗?调试动画时,我什至不知道从哪里开始。任何输入表示赞赏:)

1 个答案:

答案 0 :(得分:0)

您不需要创建折叠动画。

您可以简单地反转创建的动画以进行扩展,例如:

rvAnimator.reverse()
arrowAnimator.reverse()

为此,您不能使用AnimatorSet,您必须像这样自己启动两个动画:

rvAnimator.start()
arrowAnimator.start()