The default animation when the Back
button is pressed is a slide from left to right. I'd like to replace that with a custom animation. I'm currently thinking that some combination of onBackPressed()
and overridePendingTransition
will do the trick, but I haven't been able to get it working.
Asked
Active
Viewed 2.4k times
40

dfetter88
- 5,381
- 13
- 44
- 55
-
Include some sample code, otherwise we have no idea what you may be doing wrong. – prestomation Jul 20 '10 at 19:59
4 Answers
111
I think you shouldn't use finish() because the data stored by the Views will be erased
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
}

Álvaro
- 1,351
- 1
- 10
- 14
-
9Take note of the super, it needs to be AFTER it, otherwise no effect. – Chris.Jenkins Jun 02 '12 at 20:01
-
2@Chris.Jenkins If you are telling that `overridepending..` should be after the `super` , Then yes. It should be after any finishing calls . the super basically calls a `finish` . so the `overrride` should be after `finish` or the `super` in this case . – NT_ Jul 25 '12 at 10:54
-
Now, is there a way to do this EXCEPT on the last back button press which would quit your app? i.e. is there a way to check the back stack and see if your app is still on it? – phreakhead Jul 30 '13 at 23:28
-
@Chris.Jenkins that is incorrect. The overridePendingTransition always goes LAST. When calling an intent overridePendingTransition goes last and even in the above example the overridePendingTransition goes last. The effect does work. I wanted to clear this up for anyone who may have gotten the wrong information from Chris' comment – portfoliobuilder May 03 '15 at 12:45
5
Figured it out. I wasn't finshing the current activity. The following code does the trick.
@Override
public void onBackPressed() {
[This Activity].this.finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}

dfetter88
- 5,381
- 13
- 44
- 55
-
8super.onBackPressed() automatically calls finish. Use that instead of calling finish manually.. – Himanshu Virmani May 24 '14 at 09:56
1
if you want no animation
follow the code in Activity
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(0,0);
}
Reference : https://developer.android.com/reference/android/app/Activity.html#overridePendingTransition(int, int)

최봉재
- 4,039
- 3
- 16
- 21
0
I wouldn't use onBackPressed()
since it's a hack when we use Fragments and we need to handle the stack, for instance. I proposed a more elegant solution here: