Viewの高さを変えて開閉アニメーションさせる (Expand/Collapse Animation)

目次

ViewPropertyAnimator

Viewのanimate()で生成してチェーンで書けるお手軽な方法ですが、bottomやheightプロパティに対応していません。移動や透明度、スケール率なら簡潔に書けるので大変便利です。内部ではValueAnimatorが使われています。これと似た書き方ができる、ViewPropertyObjectAnimatorライブラリもあります。

ObjectAnimator

bottomプロパティを指定しても動作しませんが、カスタムプロパティを設定できます。他でも再利用したい場合はこれが良いかも。

fun onClick(view: View) {
    val height = 800
    val animator = ObjectAnimator.ofInt(view, HeightProperty(), height)
    animator.duration = 350
    animator.interpolator = FastOutSlowInInterpolator()
    animator.start()
}

private class HeightProperty: Property<View, Int>(Int::class.java, "height") {

    override operator fun get(view: View): Int = view.height

    override operator fun set(view: View, value: Int) {
        view.layoutParams.height = value
        view.requestLayout()
    }
}

ValueAnimator

ObjectAnimatorのスーパークラス。変化させる内容を具体的に設定できます。

fun onClick(view: View) {
    val height = 800
    ValueAnimator.ofInt(view.height, height).apply {
        duration = 350
        interpolator = FastOutSlowInInterpolator()
        addUpdateListener {
            view.layoutParams.height = it.animatedValue as Int
            view.requestLayout()
        }
        start()
    }
}