首页 > 解决方案 > animation.hasEnded 不像我预期的那样工作。为什么?

问题描述

在我的应用程序中,我有一个动画。我想等到动画完成才能继续其余的代码。我正在尝试按如下方式使用 .hasEnded 但不起作用。我知道还有其他一些技术可以实现这一点,但我想知道这段代码有什么问题。它在 while 循环中进入无限循环

myplayer= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.myanim1);
    textView_title.setAnimation(myplayer);
    
    while (!myplayer.hasEnded()){
    }

标签: androidanimation

解决方案


您可以使用新线程来测试hasEnded

        Animation myplayer= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.myanim1);
        .....
        //start the animation

        Thread thread = new Thread(){
             @Override
             public void run() {
                 super.run();
                 boolean flag = true;
                 while (flag){
                     try {
                         Thread.sleep(1000);
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                     Log.d(TAG, "run: " + myplayer.hasEnded());
                     if(myplayer.hasEnded()){
                         flag = false;
                     }
                 }
             }
         };
         thread.start();

在此处输入图像描述


可以使用以下代码来监听动画:

    Animation myplayer= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.myanim1);
        myplayer.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    textView_title.setAnimation(myplayer);

推荐阅读