Android-Translate动画第一次工作,但不是第二次

Android-Translate动画第一次工作,但不是第二次,android,android-animation,Android,Android Animation,我有一个动画,它通过平移X值对编号的球进行排序。它第一次工作时效果很好,但是当我生成新的数字并尝试再次排序时,它并没有按预期工作 第一个问题是它工作正常 所以在这里我点击排序按钮,球被正确地排序 在下一个gif中,我生成了一个新的数字,然后尝试进行排序,但正如您所看到的,我得到了一些奇怪的行为 它几乎就像是在使用旧的X值进行转换 下面是触发动画的排序方法 private fun sort() { val animator = AnimatorSet()

我有一个动画,它通过平移X值对编号的球进行排序。它第一次工作时效果很好,但是当我生成新的数字并尝试再次排序时,它并没有按预期工作

第一个问题是它工作正常

所以在这里我点击排序按钮,球被正确地排序

在下一个gif中,我生成了一个新的数字,然后尝试进行排序,但正如您所看到的,我得到了一些奇怪的行为

它几乎就像是在使用旧的X值进行转换

下面是触发动画的排序方法

  private fun sort() {
        val animator = AnimatorSet()

        val sorted = balls.sortedBy { x -> x.value }

        sorted.forEachIndexed { index, ball ->
            if (balls[index] == ball) {
                return@forEachIndexed
            }

            val occupyingBall = balls[index]
            val startingPos = balls.indexOf(ball)

            // move starting ball to occupying ball
            val occupyingRect = calculateRectOnScreen(occupyingBall)
            val startingRect = calculateRectOnScreen(ball)

            val move = getMoveAnimation(ball, startingPos, balls.indexOf(occupyingBall), occupyingRect, startingRect)
            animator.play(move)

            animator.start()
        }

        balls.clear()
        balls.addAll(sorted)
    }
下面是创建对象动画的
getMoveAnimation
方法

private fun getMoveAnimation(view: View, startingIndex: Int, finishingIndex: Int, rect1: RectF, rect2: RectF): ObjectAnimator {
        val distance = if (startingIndex > finishingIndex) {
            // Move left
            -Math.abs(rect1.right - rect2.right)
        } else {
            // Move right
            Math.abs(rect1.right - rect2.right)
        }

        return ObjectAnimator.ofFloat(view, "translationX", distance)
    }
下面是计算视图之间距离的
calculateRecontScreen
方法

 private fun calculateRectOnScreen(view: View): RectF {
        val location = IntArray(2)
        view.getLocationOnScreen(location)
        return RectF(location[0].toFloat(), location[1].toFloat(), (location[0] + view.measuredWidth).toFloat(), (location[1] + view.measuredHeight).toFloat())
    }

是否尝试将view.getTranslationX添加到位置[0].toFloat?我不熟悉getLocationOnScreen(),所以我不确定它是否只返回视图的原始位置,或者是否能够“补偿”由translation@W0rmH0le是的,我尝试过,但没有效果。是否尝试将view.getTranslationX添加到位置[0]。toFloat?我不熟悉getLocationOnScreen(),所以我不确定它是否只返回视图的原始位置,或者是否能够“补偿”由translation@W0rmH0le是的,我试过了,但没有效果。