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

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


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

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


Basically overriding onBackPressed is a proper approach, but rather than call finish() from it i would say that is better to call super.onBackPressed() and then add overridePendingTransition so we are a bit more consistent with the inheritance rules.

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


Even though overriding onBackPressed() is a good option, I would suggest overriding the finish() method, just in case the activity is finished in some other way, like a navigation action or any other view action that "destroys" the activity:

@Override public void finish() {   super.finish();   overridePendingTransition(0,0);}

We need to have in consideration that this method will be triggered after the back button has been pressed, so we are good to go :-)

Update: Moreover, overriding onBackPressed() could mess up with the Activity if we are using fragments in it, because we probably don't want to be overriding the transitions every time the back is pressed.