可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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!
回答1:
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); }
回答2:
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.
@Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.comming_in, R.anim.comming_out); }
回答3:
if you use fragment you can proceed like this :
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.setCustomAnimations(R.anim.anim_slide_in_left, R.anim.anim_slide_out_left, R.anim.anim_slide_out_right, R.anim.anim_slide_in_right); transaction.replace(R.id.fragment_container, new YourClassFragment); transaction.addToBackStack(null); transaction.commit();
anim_slide_in_left
anim_slide_out_left
anim_slide_out_right
anim_slide_in_right
回答4:
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.