androidandroid-fragmentsback-stackfragmenttransaction

Can not add to Fragment Back Stack


I open "Activity A". "Activity A" immediately does a FragmentTransaction like this to Open "Fragment A":

FragmentTransaction t = fm.beginTransaction();
ListFragment f = new ProfileFragment();
t.replace(R.id.main_frag, f, "act_frag");
f.setArguments(args);
t.commit();

"Fragment A" has a button on it that I would like to open a new Fragment ("Fragment B"), but keep the "Fragment A" in the backstack -- so if the user hits back, it is still around. So I do this:

FragmentTransaction t = fm.beginTransaction();
ListFragment f = new FollowFragment();
String username = tvUser.getText().toString();
Bundle args = new Bundle();
args.putString("follow", "watching");
args.putString("userprofile", username);
args.putInt("userIdprofile", userId);
f.setArguments(args);
t.replace(R.id.main_frag, f, "watching_frag");
t.addToBackStack("watching_frag");
t.commit();

I thought by adding t.addToBackStack(null); would do the trick; and I have done it before like that. But instead, when user hit's back, it simply closes "Activity A".


Solution

  • By default, when the back button is pressed, the activity is closed. I think for what you are trying to do, you'll have to override the method onBackPressed and add code to handle that for example:

    @Override
    public void onBackPressed() {
    
        FragmentManager fm = getSupportFragmentManager();
        if(fm.getBackStackEntryCount() > 0){
            fm.popBackStack();
            return;
        }
        super.onBackPressed();
    }
    

    This way, when back is pressed, it'll first check if there are any backstack entries and popback when back is pressed, if not, the default action is called.