Search code examples
androidtranslate-animation

How can i create left to right and then inverse animation in android?


How can I create one animation which always translates from left to right and then if animation stops it turns the other way and translates from right to left. I can create Translate animation in xml and programatically too.


Solution

  • Create this xml, it will translate from left to right and from right to left.

    /res/anim/translate.xml

    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android"
        android:fillEnabled="true"
        android:fillAfter="true" >
    
        <translate
            android:interpolator="@android:anim/linear_interpolator"
            android:fromXDelta="0%p"
            android:toXDelta="10%p"
            android:duration="2000"
            android:startOffset="0" />
    
        <translate
            android:interpolator="@android:anim/linear_interpolator"
            android:fromXDelta="10%p"
            android:toXDelta="-10%p"
            android:duration="2000"
            android:startOffset="2000" />
    
    </set>
    

    Suppose you want to apply this animation to an image then write the code below in your class file.

    ImageView image = (ImageView)findViewById(R.id.imageView1);
    Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.translate);
    image.startAnimation(animation);
    

    Edit:

    If you want your animation to repeat infinitely add the following attributes to the translate tag.

    android:repeatCount="infinite"
    android:repeatMode="restart"