2017-05-17 2 views
1

Ich versuche Animation meine Ansicht zu schütteln, schreibe ich diesen Code, aber es scheint mir, dass es möglich ist, es einfacher zu machenAnimationssatz, schütteln Effekt

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() 
    } 

Wie kann ich es tun einfacher?

Antwort

1

Sie können einige Funktionen und Felder extrahieren die Duplizierung zu reduzieren:

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 
     } 

Dann wird es nur so aussehen:

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

Die guten Methodennamen die Notwendigkeit für Zwischenvariablen entfernt haben, die hat Kürzere den Code weiter.

Verwandte Themen