40

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.

1
  • Include some sample code, otherwise we have no idea what you may be doing wrong. Commented Jul 20, 2010 at 19:59

4 Answers 4

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Take note of the super, it needs to be AFTER it, otherwise no effect.
@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 .
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?
@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
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);
}

1 Comment

super.onBackPressed() automatically calls finish. Use that instead of calling finish manually..
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)

Comments

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:

https://stackoverflow.com/a/43725255/689723

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.