通常我们切换Fragment时,都是使用系统默认的动画。这里教大家一个可以从左右平滑切换的动画效果。
在3.0以后,我们可以使用android.app.Fragment和ObjectAnimator来实现:
getFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.fragment_slide_right_in, R.animator.fragment_slide_left_out,
R.animator.fragment_slide_left_in, R.animator.fragment_slide_right_out)
.replace(R.id.your_fragment, YourFragment.newInstance())
.commit();
看到上面的代码,你一定会想到在四个动画xml里面编写移动的动画,根据自身的百分比来移动。是的,我们的思路确实是这样的。
经过测试,Fragment执行切换的时动画针对的View是我们Fragment最外层的View,可是ObjectAnimator自身是不包含百分比移动的。不过ObjectAnimator有一个很强的能力,它可以对任何拥有setXXX的方法的对象进行修改值的操作,这也是得益于它的父类ValueAnimator,所以在这里我们首先需要定义一个layout:FractionTranslateLayout。
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
/**