简体   繁体   中英

How to repeat Android animation in java?

i have this code here. I want that the Imageview do the animation 5 times. How i need to set the setRepeatCount? How to inilize it?

private void flipCoin() {
    final Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher_background);
    final ImageView iv = ((ImageView) findViewById(R.id.imageView));
    iv.setRotationY(0f);
    //iv.animate().setDuration(10);
    iv.animate().rotationY(90f).setListener(new Animator.AnimatorListener() {

        @Override
        public void onAnimationStart(Animator animation) {
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            iv.setImageDrawable(drawable);
            iv.setRotationY(270f);
            iv.animate().rotationY(360f).setListener(null);

        }

        @Override
        public void onAnimationCancel(Animator animation) {
        }
    });

The method setRepeatCount belongs to Animation class, you are using Animator .

Try this:

int times = 5;

private void flipCoin() {
    final Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher_background);
    final ImageView iv = findViewById(R.id.imageView);
    iv.setRotationY(0f);
    //iv.animate().setDuration(10);
    final ViewPropertyAnimator viewPropertyAnimator = iv.animate();
    viewPropertyAnimator.rotationY(90f);
    viewPropertyAnimator.setListener(new Animator.AnimatorListener() {

        @Override
        public void onAnimationStart(Animator animation) {
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
        }

        @Override
        public void onAnimationEnd(Animator animation) {

            times--;
            if (times > 0) {
                iv.setImageDrawable(drawable);
                iv.setRotationY(270f);
                viewPropertyAnimator.rotationY(360f);
                viewPropertyAnimator.start(); //Restart
            }
        }

        @Override
        public void onAnimationCancel(Animator animation) {
        }
    });

    viewPropertyAnimator.start(); //Init
}

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