0

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".

TheLettuceMaster
  • 15,594
  • 48
  • 153
  • 259

2 Answers2

1

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.

EboMike
  • 76,846
  • 14
  • 164
  • 167
Eric
  • 76
  • 2
  • Wait.. is the fragment transaction for adding 'Fragment B' occurring within 'Fragment A' or the Activity? – Eric Oct 27 '14 at 18:03
  • It is recurring in Fragment B. Now that I think about it, that isn't always best practice if I recall. (`Fragments` communicating to each other). But the point of what I need still stands regardless of that. – TheLettuceMaster Oct 27 '14 at 18:05
0

Have you tried putting some value inside t.addtoBackStack instead of just null? I can't test it right now but I think that might be your problem.

Vextil
  • 191
  • 1
  • 1
  • 8