简体   繁体   中英

Android Studio - Looping animation when button is pressed

I'm working on making an animation that plays when I press I button. This animation is composed of 3 frames I have made.

As of now, when I press the button, the animation starts, but doesn't stop, it just keeps looping over and over again.

What I would like is the following:

When you press the button, the animation plays once. It doesn't play until you press the button again. HOWEVER, if you press the button while the animation is playing (AKA interrupt the animation before it finishes), the animation will restart.

Here is the code I have that plays the animation when the button is pressed:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button start = (Button) findViewById(R.id.button);

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ImageView bun = (ImageView)findViewById(R.id.imageView);
                bun.setImageResource(R.drawable.buns);
                AnimationDrawable buns = (AnimationDrawable)bun.getDrawable();
                buns.start();
            }
        });

    }
}

I'm aware that you can write:

buns.setOneShot(true)

and that will cause the animation to play one time and then stop, but this isn't the solution I'm looking for.

Thanks!

Update:

I figured out the solution to this, in case anyone else was having problems.

It seems if I add the line:

buns.setOneShot(true);

after

buns.start()

this will have the intended affect, since the animation will stop after you click it and won't start until you click it again.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM