Android - wait for animation to finish before cont

2019-07-16 01:45发布

I've spend quite a while trying to find out how to wait for an animation to finish before continuing the code. So far I've tried while(animation.hasEnded() == False), using Thread.sleep, using a timer but can't seem to get anything to work.

Something that cropped up quite a few times was to add an Animation Listener to the animation, which I've tried but not sure how to progress this further.

I create the animation, start the animation and then have a line of code after, which I only want to be executed after the animation has finished:

    Animation moveDown = allAnimStuff(duration); //creates animation 

    image.startAnimation(moveDown); // Start the animation
    displayScore(score); // wait for animation to finish before executing this line

and here is the allAnimStuff(duration) method used to create the animation:

private Animation allAnimStuff(final long duration) {

        Animation moveDown = new TranslateAnimation(image.getX(), image.getX(), (-image.getHeight()), pxHeight - image.getHeight() / 2); //creates animation
        moveDown.setDuration(duration);
        moveDown.setFillAfter(false);

        moveDown.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                 //some code to make it wait here? 
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                image.setY((pxHeight / 2 - image.getHeight()));

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });


        return moveDown;
    }

1条回答
可以哭但决不认输i
2楼-- · 2019-07-16 02:26

write following line in onAnimationEnd method

 displayScore(score);

for example

private Animation allAnimStuff(final long duration) {

        Animation moveDown = new TranslateAnimation(image.getX(), image.getX(), (-image.getHeight()), pxHeight - image.getHeight() / 2); //creates animation
        moveDown.setDuration(duration);
        moveDown.setFillAfter(false);

        moveDown.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                 //some code to make it wait here? 
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                image.setY((pxHeight / 2 - image.getHeight()));
             displayScore(score);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });


        return moveDown;
    }
查看更多
登录 后发表回答