通过动画在活动中交换片段

我想通过动画交换一个活动中的两个片段。假设 PageA 代表片段 A,在屏幕的左侧,而 PageB 代表片段 B,即在屏幕的右侧。现在我希望当我点击一个按钮,然后 PageA 将移动到屏幕的右侧与一些过渡动画。

我尝试用下面的代码来替换这个位置

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, new FragB());
fragmentTransaction.commit();

寻找线索。

先谢谢你。

94876 次浏览

Old questiion and you probably already figured it out, but for future reference:

here's what you use to set a custom animation when you replace a fragment via code:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();


ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
ft.replace(R.id.fragment_container, newFragment, "fragment");
// Start the animated transition.
ft.commit();

Here is an example of the slide_in_left animation:

<?xml version="1.0" encoding="utf-8"?>
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="-100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="500"/>
</set>

Note that this is the animation if you are using the compatibility library. Instead if you are using and SDK with native support for the FragmentManager then your animation will look like this:

<?xml version="1.0" encoding="utf-8"?>
<set>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="x"
android:valueType="floatType"
android:valueFrom="-1280"
android:valueTo="0"
android:duration="500"/>
</set>

This is because the compatibility library does not support the new objectAnimator type and instead only implement the old animation framework.