Проблема с анимацией для кастомного ViewGroup

Есть задача создать кастомный ViewGroup виджет, в который можно добавить только два дочерних элемента. Оба центрированы по горизонтали, первый должен размещаться на верхней границе родительского кастомного ViewGroup, второй - на нижней границе. При добавлении должна проигрываться анимация: дочерний элемент медленно появляется в середине ViewGroup и перемещается на верхнюю границу (для первого элемента) или на нижнюю (для второго элемента) за фиксированное время. Вот мой код:

class CustomViewGroup @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    @AttrRes defStyleAttr: Int = 0,
    @StyleRes defStyleRes: Int = 0
) : ViewGroup(context, attrs, defStyleAttr, defStyleRes) {

    private val timeDuration = 2000L
    private val maxChild = 2

    override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {
        if (childCount > 0) {
            val firstChild = getChildAt(0)

            if (firstChild != null) {
                firstChild.layout(
                    measuredWidth / 2 - firstChild.measuredWidth / 2,
                    0,
                    measuredWidth / 2 + firstChild.measuredWidth / 2,
                    firstChild.measuredHeight
                )
            }
        }

        if (childCount > 1) {
            val secondChild = getChildAt(1)

            if (secondChild != null) {
                secondChild.layout(
                    measuredWidth / 2 - secondChild.measuredWidth / 2,
                    measuredHeight - secondChild.measuredHeight,
                    measuredWidth / 2 + secondChild.measuredWidth / 2,
                    measuredHeight
                )
            }
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        var maxWidth = 0
        var totalHeight = 0

        for (i in 0 until childCount) {
            val child = getChildAt(i)
            measureChild(child, widthMeasureSpec, heightMeasureSpec)
            maxWidth = Math.max(maxWidth, child.measuredWidth)
            totalHeight += child.measuredHeight
        }

        val width = resolveSize(maxWidth, widthMeasureSpec)
        val height = resolveSize(totalHeight, heightMeasureSpec)

        setMeasuredDimension(width, height)
    }

    override fun addView(child: View?) {

        if (childCount > 2) {
            throw IllegalStateException("Custom view can only have $maxChild children")
        } else {
            super.addView(child)

            if (child != null) {
                startAnimation(child, childCount - 1)
            }
        }
    }

    private fun startAnimation(child: View, childIndex: Int) {
        child.alpha = 0f
        val startY = measuredHeight.toFloat() / 2
        val endY = if (childIndex == 0) 0f else measuredHeight.toFloat() - child.measuredHeight

        val translateYAnimator = ObjectAnimator.ofFloat(child, "y", startY, endY)
        val fadeAnimator = ObjectAnimator.ofFloat(child, "alpha", 0f, 1f)

        val animatorSet = AnimatorSet()
        animatorSet.playTogether(translateYAnimator, fadeAnimator)
        animatorSet.duration = timeDuration
        animatorSet.interpolator = DecelerateInterpolator()
        
        animatorSet.start()
    }
}

Проблема в том, что при добавлении дочернего View элемента анимация перемещения не проигрывается, при этом анимация медленного появления видна. Подскажите, пожалуйста, что может быть не так.


Ответы (0 шт):