Android 开发中为了适应Android碎片问题,我们会经常使用到Fragment,管理Fragment不被重复加载的需求屡见不鲜,废话少说先上两个方法
第一次加载Fragment时调用这个方法,即当Fragment为空时。
public void addFragment(Fragment fragment,String tag){
transaction =manager.beginTransaction();
if (showfragment==null){
}else {
transaction.hide(showfragment);
}
transaction.add(R.id.fg,fragment);
transaction.commit();
showfragment=null;
showfragment=fragment;
Log.i("当前的fragment", showfragment.toString() + "/" + tag);
}
切换Fragment时调用如下方法
//切换页面的重载,优化了fragment 的切换
public void switchFragment(Fragment from,Fragment to){
if(from==null||to==null){
return ;
}else {
FragmentTransaction transaction=manager.beginTransaction();
if (!to.isAdded()){
//隐藏当前的fragment,
transaction.hide(from).add(R.id.fg,to).commit();
}else {
transaction.hide(from).show(to).commit();
}
showfragment=to;
}
}
举个列子
需求,有4个切换的首页页面,相当于四个Fragment
FragmenTone fragmenOne;
FragmentTwo fragmentTwo;
FragmentThree fragmentThree;
FragmentFour fragmentFour;
当然首先要初始化:
FragmentManager manager;//Fragment管理者
FragmentTransaction transaction;//Fragment事务管理者
Fragment showfragment;//当前页,即将要隐藏的页面,就是
switchFragment()这个方法的第一个参数
并且在加载Fragment之前,一般在onCreat方法中获取到
FragmentManager :
manager=getSupportFragmentManager();</pre>
开始加载Fragment了:
swich(getId){//按钮id
case R.id.xx1:
if (fragmenOne==null){
fragmenOne=new FragmenTone ();
addFragment(fragmenOne,"one");
}else {
switchFragment(showfragment,fragmenOne);
}
beack;
case R.id.xx2:
if (fragmentTwo==null){
fragmentTwo=new FragmentTwo ();
addFragment(fragmentTwo,"two");
}else {
switchFragment(showfragment,fragmentTwo);
}
beack;
case R.id.xx3:
if (fragmentThree==null){
fragmentThree=new FragmentThree ();
addFragment(fragmentThree,"three");
}else {
switchFragment(showfragment,fragmentThree);
}
beack;
case R.id.xx4:
if (fragmentFour==null){
fragmentFour=new FragmentFour ();
addFragment(fragmentFour,"four");
}else {
switchFragment(showfragment,fragmentFour);
}
beack;
}
ok,好了,就这样。可能封装性不怎么好,但是还可以用。
Fragment--》回退栈
先下班赶火车,下次补上。