动画设置,摇动效果

时间:2017-05-17 15:50:08

标签: android android-animation kotlin

我试着动摇我的观点,我写这段代码,但在我看来,它可以让它更容易

 var animatorSet = AnimatorSet()
    var objectRotateAnimator = ObjectAnimator.ofFloat(shake, "rotation", -5f, 5f)
    objectRotateAnimator.apply {
        repeatMode = ValueAnimator.REVERSE
        repeatCount = ValueAnimator.INFINITE
        duration = 70
        interpolator = LinearInterpolator()
    }

    var objectTranslateAnimator = ObjectAnimator.ofFloat(shake, "translate", -5f, 5f)
    objectTranslateAnimator.apply {
        repeatMode = ValueAnimator.REVERSE
        repeatCount = ValueAnimator.INFINITE
        duration = 70
        interpolator = LinearInterpolator()
    }

    start_shake.setOnClickListener {
        animatorSet.play(objectRotateAnimator).with(objectTranslateAnimator)
        animatorSet.start()
    }

我怎样才能更简单?

1 个答案:

答案 0 :(得分:1)

您可以提取一些功能和字段以减少重复:

private val linearInterpolator = LinearInterpolator()

private fun shakeAnimator(propertyName: String) =
        ObjectAnimator.ofFloat(shake, propertyName, -5f, 5f).apply {
            repeatMode = ValueAnimator.REVERSE
            repeatCount = ValueAnimator.INFINITE
            duration = 70
            interpolator = linearInterpolator
        }

然后它看起来像:

start_shake.setOnClickListener {
    AnimatorSet().apply {
        play(shakeAnimator("rotation")).with(shakeAnimator("translate"))
        start()
    }
}

好的方法名称已经消除了对中间变量的需求,这些变量进一步缩短了代码。