How to achieve shake animation programmatically?

Just to provide another possible answer to the question. The below animation file need to be put under res/anim folder :

shake.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:interpolator="@android:anim/linear_interpolator">

    <translate
        android:duration="66"
        android:fromXDelta="0%p"
        android:toXDelta="-2%p" /> <!-- -2 -->

    <translate
        android:duration="66"
        android:fromXDelta="0%p"
        android:startOffset="66"
        android:toXDelta="4%p" /> <!-- 2 -->

    <translate
        android:duration="66"
        android:fromXDelta="0%p"
        android:startOffset="132"
        android:toXDelta="-4%p" /> <!-- -2 -->

    <translate
        android:duration="66"
        android:fromXDelta="0%p"
        android:startOffset="198"
        android:toXDelta="4%p" /> <!-- 2 -->

    <translate
        android:duration="66"
        android:fromXDelta="0%p"
        android:startOffset="264"
        android:toXDelta="-3%p" /> <!-- -1 -->

    <translate
        android:duration="66"
        android:fromXDelta="0%p"
        android:startOffset="330"
        android:toXDelta="2%p" /> <!-- 1 -->

    <translate
        android:duration="66"
        android:fromXDelta="0%p"
        android:startOffset="396"
        android:toXDelta="-1.5%p" /> <!-- -0.5 -->

    <translate
        android:duration="66"
        android:fromXDelta="0%p"
        android:startOffset="462"
        android:toXDelta="1%p" /> <!-- 0.5 -->

    <translate
        android:duration="66"
        android:fromXDelta="0%p"
        android:startOffset="528"
        android:toXDelta="-0.5%p" /> <!-- 0 -->

</set>

And to use it in code (Here in Kotlin) :

val animShake = AnimationUtils.loadAnimation(requireContext(), R.anim.shake)
mView.startAnimation(animShake)

Animation explanation:

  • If you want 1000ms of duration, you need to divide this by the number of step in your anim. Ex. with 5 steps: 1000/5 = 200 So if you put 200 of duration for each step, all will take same time to end

  • The "startOffset" parameter need to specify after what time the animation need to start (Here we wanted to sum all of before operations)

  • The "fromXDelta" parameter is your started point at each step, based on the previous step.


let's say that mView is the view you want to animate:

ObjectAnimator
  .ofFloat(mView, "translationX", 0, 25, -25, 25, -25,15, -15, 6, -6, 0)
  .setDuration(duration)
  .start();

Tags:

Android