1.用add方法进行添加
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
//得到Fragment的管理类
FragmentManager fragmentManager = getSupportFragmentManager();
//开启事务
transaction = fragmentManager.beginTransaction();
/**
* 这是一个方法,用于隐藏所有的Fragment。
*/
hideFragment(aFragment);
hideFragment(bFragment);
hideFragment(cFragment);
hideFragment(dFragment);
switch (menuItem.getItemId()) {
case R.id.item1:
if (aFragment == null) {//如果没有fragment,开始创建并且添加
aFragment = new AFragment();
transaction.add(R.id.fl, aFragment);
} else {//有Fragment就让它显示
transaction.show(aFragment);
}
dl.closeDrawer(Gravity.LEFT);//关闭侧滑菜单
break;
case R.id.item2:
if (bFragment == null) {
bFragment = new BFragment();
transaction.add(R.id.fl, bFragment);
} else {
transaction.show(bFragment);
}
dl.closeDrawer(Gravity.LEFT);
break;
case R.id.item3:
if (cFragment == null) {
cFragment = new CFragment();
transaction.add(R.id.fl, cFragment);
} else {
transaction.show(cFragment);
}
dl.closeDrawer(Gravity.LEFT);
break;
case R.id.item4:
if (dFragment == null) {
dFragment = new DFragment();
transaction.add(R.id.fl, dFragment);
} else {
transaction.show(dFragment);
}
dl.closeDrawer(Gravity.LEFT);
break;
}
transaction.commit();
return true;
}
//隐藏Fragment
private void hideFragment(Fragment fragment) {
if (fragment != null) {
transaction.hide(fragment);
}
}
2.用replace方法进行替换
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.item1:
aFragment = new AFragment();
getFragment(aFragment);
dl.closeDrawer(Gravity.LEFT);
break;
case R.id.item2:
bFragment = new BFragment();
getFragment(bFragment);
dl.closeDrawer(Gravity.LEFT);
break;
case R.id.item3:
cFragment = new CFragment();
getFragment(cFragment);
dl.closeDrawer(Gravity.LEFT);
break;
case R.id.item4:
dFragment = new DFragment();
getFragment(dFragment);
dl.closeDrawer(Gravity.LEFT);
break;
}
transaction.commit();
return true;
}
private void getFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fl,fragment);
transaction.commit();
}
add其中主要用了FragmentTransaction的show和hide方法,当然,用replace方法也能实现,但是replace方法相比而言 比用show和hide方法要浪费资源,如果加载的是网络数据用replace就比较耗费流量了,因为replace方法其实就是remove方法和add方法的结合,当我们加载布局文件后不需要显示的时候就remove掉,当用的时候再去加载,这个中间要耗资源,如果用show和hide方法的话,如果用到某个布局,那我们就show,不显示布局就hide,这样避免了重复加载.
网友评论