Android中Fragment之间切换我们是可以对其进行添加动画,而且进行设置也是非常简单,但是在设置动画的过程中有一些需要注意的地方后面会慢慢说出来
- 这里我直接贴出Fragment切换的方法上面有注释
public static void showFragment(int index, int state) {
// 想要显示fragment,先隐藏所有fragment,防止重叠
mineChangestate = state;
marketChangestate = state;
FragmentTransaction ft = manager.beginTransaction();
//fragment的切换动画
if(index ==0 && last_index ==0){
ft.setCustomAnimations(R.anim.fragmen_left, 0);
}
if(index != last_index) {
if (index - last_index > 0) {
ft.setCustomAnimations(R.anim.fragmen_left, 0);
} else if (index - last_index < 0) {
ft.setCustomAnimations(R.anim.fragment_right, 0);
}
}
hideFragments(ft);
switch (index) {
case 1:
//判断是否点击推荐按钮
// 如果fragment1已经存在则将其显示出
last_index =1;
if (fragment1 != null) {
if (marketChangestate == 1) {
ft.remove(fragment1);
fragment1 = new RecommendFragment();
ft.add(R.id.main_framelayout, fragment1);
marketChangestate = 0;
}
ft.show(fragment1);
// 否则是切换则添加fragment1,注意添加后是会显示出来的,replace方法也是先remove后add
} else {
fragment1 = new RecommendFragment();
ft.add(R.id.main_framelayout, fragment1);
}
break;
case 2:
//是否点击理财按钮
last_index =2;
if (fragment2 != null) {
if (marketChangestate == 1) {
ft.remove(fragment2);
fragment2 = new MarketFragment();
ft.add(R.id.main_framelayout, fragment2);
marketChangestate = 0;
}
ft.show(fragment2);
} else {
fragment2 = new MarketFragment();
ft.add(R.id.main_framelayout, fragment2);
}
break;
case 3:
//是否点击我的按钮
last_index =3;
if (fragment3 != null) {
if (mineChangestate == 1) {
ft.remove(fragment3);
fragment3 = new MineFragment();
ft.add(R.id.main_framelayout, fragment3);
mineChangestate = 0;
}
ft.show(fragment3);
} else {
fragment3 = new MineFragment();
ft.add(R.id.main_framelayout, fragment3);
}
break;
}
ft.commitAllowingStateLoss();
}
上面那么多代码,其实设置Fragment切换动画的只有一句代码,下面就是设置Fragment的动画
ft.setCustomAnimations(R.anim.fragmen_left, 0);
但是需要注意的是在设置动画的时候一定要在Fragment show之前进行设置否则该动画就不会起作用
下面在贴出动画代码,我设置的动画是平移动画
代码路径res/anim/fragmen_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="-100%p"
android:toXDelta="0"
android:duration="400"/>
</set>