Android - 如何在按下默认后退按钮时为活动过渡设置动画

问题描述:

在我的活动中,我有一个带有以下点击侦听器的按钮,效果很好:

In my activity, I have a button with the following click listener that is working great:

final ImageButton startOverButton = (ImageButton) findViewById(R.id.start_over_button);
startOverButton.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(final View v) {

        finish();//go back to the previous Activity
        overridePendingTransition(R.anim.comming_in, R.anim.comming_out);
    }
});

它以我想要的方式动画返回上一个活动.但是,当用户按下 Android 默认的后退按钮时,不会触发动画.我的问题是:我应该把动画代码放在哪里 overridePendingTransition(R.anim.comming_in, R.anim.comming_out); 以便当用户点击我的按钮和输入时触发这个动画默认的 Android 后退按钮?

It animates the return to the previous activity the way I want. However, when the user presses the Android default back button, the animation is not triggered. My question is: where should I put the animation code overridePendingTransition(R.anim.comming_in, R.anim.comming_out); so that this animation will be triggered both when the user clicks on my button and in the default Android back button?

作为一个天真的尝试,我尝试将 overridePendingTransition(R.anim.comming_in, R.anim.comming_out); 代码行放在 onDestroy() 方法,但没有用.

As a naive try, I have tried to put the overridePendingTransition(R.anim.comming_in, R.anim.comming_out); line of code in the onDestroy() method but it did not work.

先谢谢你!

也许你可以在 Activity 中的 onBackPressed() 方法中完成这项工作.

maybe you can do this work in onBackPressed() method in the activity.

@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.comming_in, R.anim.comming_out);   
}