show/hide fragments and adding it to backstack
I have a menu with 4 menu options... Each of these options shows the
corresponding fragment. I have 3 functions to add,show and hide a
fragment:
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();
}
}
The navitemswitchlogic is as follows:
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
}
}
Problem: When I go from Fragment 1 to 2 and hit back button - an empty
screen shows up.. hitting back again takes me to fragment 1.. now, when I
try loading fragment 2 from the menu an empty screen shows up.. I know I
am making some mistake adding and retrieving fragments to/from the
backstack..But,I am not sure what exactly it is. Also, I dont want to
replace the fragments... Hope I framed my question right.. Any help is
appreciated.Thanks!
No comments:
Post a Comment