Delays within the Animation (TranslateAnimation)

29,423

Solution 1

Here is an example:

First the layout (main.xml) with an image we would like to animate:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

Next one is the animation. Placed in res/anim and is called anim_img.xml. The file contains the translation animation with android:startOffset="500" (in millisec). This will set the offset, which is used every time animation starts:

<?xml version="1.0" encoding="utf-8"?>
<set>

    <translate
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:fromXDelta="0%"
        android:fromYDelta="0%"
        android:toXDelta="0%"
        android:toYDelta="100%"
        android:zAdjustment="top" 
        android:repeatCount="infinite"
        android:startOffset="500"/>

</set>

And last but not least - the activity. Which starts the animation:

public class StackOverflowActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ImageView iv_icon = (ImageView) findViewById(R.id.imageView1);

        Animation a = AnimationUtils.loadAnimation(this, R.anim.anim_img);
        a.setFillAfter(true);
        a.reset();

        iv_icon.startAnimation(a);
    }
}

Solution 2

To achieve a pause of x milliseconds between each restart:

myAnimation.setAnimationListener(new AnimationListener(){

        @Override
        public void onAnimationStart(Animation arg0) {
        }
        @Override
        public void onAnimationEnd(Animation animation) {
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            myAnimation.setStartOffset(x);
        }

    });
Share:
29,423
ymotov
Author by

ymotov

Updated on April 29, 2020

Comments

  • ymotov
    ymotov about 4 years

    Is there a way to have the Animation pause for a half a second?

    I am trying to make an infinite animation using the TranslateAnimation API. So, I use the RepeatCount as Infinite. I also noticed that there's a setStartOffset(...) method that covers the case when I'd like to have a delay in starting the animation. However, I can't find a way to have a delay before each 'restart'. Since animation is gonna happen infinite amount of times, every time the animation restarts I need to put a delay in.

    Any ideas?

    Thanks!!