我有一个包含4个菜单选项的菜单...每个选项都显示相应的片段。 我有3个函数来添加,显示和隐藏片段:
private void addFragment(Fragment newFragment, String fragmentName) {
fragmentManager
.beginTransaction()
.add(R.id.content_frame, newFragment,
fragmentName).addToBackStack(null)
.commit();
}
private void hideFragment(Fragment existingFragment) {
if(existingFragment!=null && existingFragment.isVisible()){
fragmentManager.beginTransaction().hide(existingFragment).addToBackStack(null).commit();
}
}
private void showFragment(Fragment existingFragment) {
if(existingFragment!=null){
fragmentManager.beginTransaction().show(existingFragment)
.addToBackStack(null).commit();
}
}
navitemswitchlogic如下:
onNavItemSelected(int id) {
switch (id) {
case 1: //option 1 - hide rest of the fragments and show Option1Fragment
hideFragment(option2Fragment);
hideFragment(option3Fragment);
hideFragment(option4Fragment);
if (Option1FragmentDoesnotExist) { //create option1Fragment and add it to FragmentTransaction
option1Fragment = new option1Fragment();
addFragment(option1Fragment,"option1Fragment");
} else
showFragment(option1Fragment);
break;
case 2:
//same as option 1
}
}
我期待发生的事情:
现在发生了什么:
我知道我在后台添加和检索碎片时犯了一些错误。但是,我不确定它究竟是什么。我尝试将所有这些作为同一交易的一部分也做了..那个工作也是如此..而且,我不想替换碎片......希望我把我的问题框起来......
感谢任何帮助。谢谢!