Theo
Theo

Reputation: 3149

How to stop images animation?

The following program displays full screen images that animate automatically by using the loadAnimation() method. Here is is the code.

public class MainActivity extends ActionBarActivity {

/** Called when the activity is first created. */
public int currentimageindex=0;
Timer timer;
TimerTask task;
ImageView slidingimage;

private int[] IMAGE_IDS = {
        R.drawable.picture1, R.drawable.picture2, R.drawable.picture3,
        R.drawable.picture4
};
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Handler mHandler = new Handler();


    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {

            AnimateandSlideShow();

        }
    };

    int delay = 1000; // delay for 1 sec.

    int period = 3000; // repeat every 4 sec.

    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {

            mHandler.post(mUpdateResults);

        }

    }, delay, period);



}



/**
 * Helper method to start the animation on the splash screen
 */
private void AnimateandSlideShow() {


    slidingimage = (ImageView)findViewById(R.id.ImageView3_Left);
    slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);

    currentimageindex++;

    Animation leftToRight = AnimationUtils.loadAnimation(this, R.anim.left_to_right);


    slidingimage.startAnimation(leftToRight);




}


}

As you can see the full sized picture change every 4 seconds. Now what i want to do is to stop the animation after the appearance of the last image(picture 4 in this case). After fixing this,I will try fetch images from a server using JSON.

Thank you, Theo.

Upvotes: 0

Views: 122

Answers (1)

user4571931
user4571931

Reputation:

1)You have to load animation until only you have image in IMAGE_IDS array

2)Then stop your timer also

Add following lines in AnimateandSlideShow() below currentimageindex++

if(currentimageindex <= IMAGE_IDS.length)
        {
            Animation leftToRight = AnimationUtils.loadAnimation(this, R.anim.letf_anim);
            slidingimage.startAnimation(leftToRight);
        }
        else
        {
            timer.cancel();
        }

Also replace following line

Timer timer = new Timer();

To

timer = new Timer();

Upvotes: 1

Related Questions