Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

How to reset a DrawableAnimation

I'm trying to create a dynamically populated frame animation for a simple slot reel. I create a random sequence of 50 animated images to make it look like the reel is spinning, then add the final three symbols at the end.

My problem is that each time this method is run, it adds the frames onto the previous Animation. The first time it is run, the animation has 53 frames, the second time it has 106 frames, etc. I want to reset/clear the animation each time it is run, but I cannot figure out how to do so. If anyone has any ideas it would be greatly appreciated!

      private void animate(int r1c1, int r2c1, int r3c1, int r1c2, int r2c2, int r3c2, int r1c3, int r2c3, int r3c3) {
        ImageView imgView = (ImageView)findViewById(R.id.animationImage);
        imgView.setVisibility(ImageView.VISIBLE);

        imgView.setBackgroundResource(R.drawable.frame_animation);

        AnimationDrawable frameAnimation = (AnimationDrawable) imgView.getBackground();



        BitmapDrawable cherry = (BitmapDrawable)getResources().getDrawable(R.drawable.cherry);
        BitmapDrawable grape = (BitmapDrawable)getResources().getDrawable(R.drawable.grape);
        BitmapDrawable lemon = (BitmapDrawable)getResources().getDrawable(R.drawable.lemon);
        BitmapDrawable lucky7 = (BitmapDrawable)getResources().getDrawable(R.drawable.lucky7);
        BitmapDrawable watermelon = (BitmapDrawable)getResources().getDrawable(R.drawable.watermelon);
        BitmapDrawable orange = (BitmapDrawable)getResources().getDrawable(R.drawable.orange);
        BitmapDrawable[] symbols = {cherry,watermelon,grape,lemon,orange,lucky7};
        frameAnimation = (AnimationDrawable) imgView.getBackground();
        for(int i = 0; i < 50; i++) {
            frameAnimation.addFrame(symbols[(int)(Math.random() * 6)], 50);

        }
        frameAnimation.addFrame(symbols[r3c1], 200);
        frameAnimation.addFrame(symbols[r2c1], 200);
        frameAnimation.addFrame(symbols[r1c1], 200);

        if (frameAnimation.isRunning()) {
            frameAnimation.stop();
            frameAnimation.start();
        }
        else {

            frameAnimation.start();
        }


    }