我正在尝试实现类似于 iOS 上的推送和弹出动画的效果。用户导航离开的 fragment 应从左侧滑出,用户导航至的 fragment 应从右侧滑入。当用户向后导航时(通过单击工具栏上的小箭头图标或按设备上的后退按钮),动画应该反转; “弹出” fragment 应向右滑出,层次结构中的前一个 fragment 应从左侧滑回。所以实际上感觉就像你在往回走,箭头指向的方向。不幸的是,我只能让第一部分发生;当用户返回时,前一个 fragment 也(违反直觉)从右侧滑入,弹出的 fragment 向左滑动! (完全反转想要的效果)。
这是我的 fragment 转换代码:
FragmentManager fManager = getSupportFragmentManager();
FragmentTransaction transaction = fManager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_left, R.anim.slide_out_right);
transaction.replace(R.id.wholeview, itemChoiceFragment, ItemChoiceFragment.class.getName());
transaction.addToBackStack("itemChoice");
transaction.commit();
这是我的动画 xml: slide_in_left.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="400"/>
</set>
slide_out_right.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="-100%"
android:startOffset="100"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="300"/>
</set>
如有任何帮助,我们将不胜感激。
谢谢。
最佳答案
代替
transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_left, R.anim.slide_out_right);
使用
transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_right, R.anim.slide_out_left);
R.anim.slide_in_right 所在
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="-100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="400"/>
</set>
和 R.anim.slide_out_left
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="100%"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="300"/>
</set>
这个方法的参数是
setCustomAnimations(int enter, int exit, int popEnter, int popExit)
基本上是这样
-进入时从右向左滑动新 fragment
-离开当前 fragment 时向左滑出
-单击返回时从左向右滑动旧 fragment
-点击返回时将当前 fragment 向右滑动
根据方法描述
FragmentTransaction setCustomAnimations (int enter,
int exit,
int popEnter,
int popExit)
Set specific animation resources to run for the fragments that are entering and exiting in this transaction. The popEnter and popExit animations will be played for enter/exit operations specifically when popping the back stack.
关于android动画向左滑出,向后反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40293351/