Tiago Tiago - 3 months ago 50
Android Question

Android - How to animate an activity transition when the default back button is pressed

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);
}
});


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?

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.

Thank you in advance!

Answer

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);   
}