android:activity过渡动画 finish 关闭activity 无效
程序员文章站
2022-05-03 09:48:05
...
这边就不介绍过渡动画了,先上我的过渡动画代码,我写的是进入的时候从下往上,退出的时候从上往下的动画。
transition文件夹两个:
bottom_ani.xml 退出动画
<?xml version="1.0" encoding="utf-8"?>
<slide xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:interpolator/decelerate_cubic"
android:slideEdge="top">
</slide>
top_ani.xml 进入动画
<?xml version="1.0" encoding="utf-8"?>
<slide xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:interpolator/decelerate_cubic"
android:slideEdge="bottom"/>
然后在activity的setContentView之前设置这两个动画:
getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
Transition top = TransitionInflater.from(this).inflateTransition(R.transition.top_ani);
getWindow().setEnterTransition(top);
Transition bottom = TransitionInflater.from(this).inflateTransition(R.transition.bottom_ani);
getWindow().setExitTransition(bottom);
启动的时候使用:
startActivity(intent,ActivityOptions.makeSceneTransitionAnimation(EventSearchActivity.this).toBundle());
但是我结束的时候,直接使用了
finish();
退出动画却没有成功显示,从startActivity看,比正常的多了参数,那结束activity应该也不会是正常的finish()。
点击手机上的返回键,退出动画就显示了,看看源码:
@Override
public void onBackPressed() {
FragmentManager fragmentManager = mFragments.getSupportFragmentManager();
final boolean isStateSaved = fragmentManager.isStateSaved();
if (isStateSaved && Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
// Older versions will throw an exception from the framework
// FragmentManager.popBackStackImmediate(), so we'll just
// return here. The Activity is likely already on its way out
// since the fragmentManager has already been saved.
return;
}
// 我用的AppCompatActivity继承的是FragmentActivity,所以上面有对于当退出时对于Fragment的操作,和动画没有关系,看下面,继续点到父类的onBackPressed
if (isStateSaved || !fragmentManager.popBackStackImmediate()) {
super.onBackPressed();
}
}
点super.onBackPressed,就到Activity类了:
public void onBackPressed() {
if (mActionBar != null && mActionBar.collapseActionView()) {
return;
}
FragmentManager fragmentManager = mFragments.getFragmentManager();
if (fragmentManager.isStateSaved() || !fragmentManager.popBackStackImmediate()) {
//下面这句话,很明显就是,启动退出动画再退出activity
finishAfterTransition();
}
}
因此,把 finish(); 替换成 finishAfterTransition();