如何让 Activity 在根据 Intent 切换到新布局之前等待?

How do I make the Activity wait before it switches to the new layout based on an Intent?

我想在单击按钮时对布局 XML 中的视图执行 Animation。然后一旦这个 Animation 完成,然后切换到新的 ActivityAnimation 需要 1.2 秒才能完全执行,但不幸的是,在 Animation 实际设法显示在屏幕上之前,页面实际上已切换到新的布局文件。这是我的 OnClickListener 的代码,其中包括 Animation 和返回的 Intent:

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

                Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_out_right);
                relativeLayout.startAnimation(animation);

                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            synchronized(this) {
                                wait(3000);
                            }
                        } catch(InterruptedException ex) {

                        }
                    }
                };
                thread.start();

                Intent resultIntent = new Intent();               
                setResult(Activity.RESULT_OK, resultIntent);
                finish();
            }
        }
    });

不幸的是,即使像上面那样添加了一个新的 Thread 来携带一个 wait 3 秒,我还是无法工作!欢迎任何想法,我也不介意是否必须使用线程。

编辑 - 答案:感谢 Gennadii Saprykin 关于使用 onAnimationEnd() 回调的建议。

    animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_out_right);

    Button button = (Button) findViewById(R.id.button);

    animation.setAnimationListener(new Animation.AnimationListener() {
        public void onAnimationStart(Animation animation) {
        }

        public void onAnimationRepeat(Animation animation) {
        }

        public void onAnimationEnd(Animation animation) {
            Intent resultIntent = new Intent();
            setResult(Activity.RESULT_OK, resultIntent);
            finish();
        }
    });

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            relativeLayout.startAnimation(animation);
        }
    });

尝试使用 onAnimationEnd 回调:http://developer.android.com/reference/android/view/animation/Animation.AnimationListener.html

在这种情况下,您的后台线程没有意义,因为它在后台等待 3 秒,但您正在 UI 线程中完成 activity。

button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_out_right);
        animation.setAnimationListener(new AnimationListener() {
            //...
            @Override
            public void onAnimationEnd(Animation animation) {
                Intent resultIntent = new Intent();               
                setResult(Activity.RESULT_OK, resultIntent);
                finish();
            }
        });
        relativeLayout.startAnimation(animation);           
    }
});