废话不多说,直接上代码
解决方法:
public Fragment switchContent(){
List<Fragment> fragments = fm.getFragments();
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
return fragment;
}
return null;
}
public void switchContent(Fragment curVisible, Fragment to) {
if (curVisible != null && to != null) {
FragmentTransaction transaction = fm.beginTransaction();
if (!to.isAdded()) { // 先判断是否被add过
transaction.hide(curVisible).add(R.id.mContent, to).commit(); // 隐藏当前的fragment,add下一个到Activity中
} else {
transaction.hide(curVisible).show(to).commit(); // 隐藏当前的fragment,显示下一个
}
}
}
在点击切换的地方这样使用:
switchContent(switchContent(), selfFragment);