首先,要用到声明Fragment管理器和Fragment事物:FragmentManage和FragmentTransaction
private FragmentManager fragmentManager=null;
private FragmentTransaction transaction=null;
先获取Fragment管理者,
fragmentManager=getFragmentManager();
然后写Fragment的切换函数:
1、先开始Fragment事物,
2、隐藏Fragment
3、选择要显示的Fragment,如果为null,则先new 它的实例,再把实例加进Fragment事物中。
如果不为空,那么,直接显示隐藏。transaction.show(fragment1);
4、非常容易忘掉的一个,事物的提交 transaction.commit();这样才可以实现Fragment的切换
下面是Fragment的隐藏函数示例:
private void hideFragment(){
if(fragment1!=null){
transaction.hide(fragment1);
}
if(fragment2!=null){
transaction.hide(fragment2);
}
if(fragment3!=null){
transaction.hide(fragment3);
}
if(fragment4!=null){
transaction.hide(fragment4);
}
}
下面是Fragment的切换函数:
private void setTag(int position){
transaction=fragmentManager.beginTransaction();
hideFragment();
switch (position){
case 0:
if(fragment1==null){
fragment1=new Fragment1();
transaction.add(R.id.fragmentView,fragment1);
}
else {
transaction.show(fragment1);
}
break;
case 1:
if(fragment2==null){
fragment2=new Fragment2();
transaction.add(R.id.fragmentView,fragment2);
}
else {
transaction.show(fragment2);
}
break;
case 2:
if(fragment3==null){
fragment3=new Fragment3();
transaction.add(R.id.fragmentView,fragment3);
}
else {
transaction.show(fragment3);
}
break;
case 3:
if(fragment4==null){
fragment4=new Fragment4();
transaction.add(R.id.fragmentView,fragment4);
}
else {
transaction.show(fragment4);
}
break;
}
transaction.commit();
}//end setTag
下面是Fragment视图的一个简单举例:
public class Fragment1 extends Fragment {
@Override
public View onCreateView(final LayoutInflater inflater,
final ViewGroup contain,final Bundle bundle){
return inflater.inflate(R.layout.fragment1,contain,false);
}//end onCreateView
}