Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Fragment.addToBackStack() causing the Back button to do nothing?

Tags:

android

  1. Activity 1 is visible. Press a button, and Activity 2 opens.
  2. Activity 2 adds fragment A to itself (and back stack) and it displays fine
  3. Pressing a button within the fragment transitions to another fragment, B
  4. Press Back. Nothing happens. Huh? The Back press is seemingly absorbed and not acted upon, the display remains the same.
  5. Press Back a second time, it reverts to the Activity 1, as expected.

Why is my fragment not being shown in step 4? I've added the fragment to the back stack, so why (when the Back button seems aware of its existence) does it not show the fragment?

Here's the code I'm using in Activity 2 to open Fragment A.

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.act_profile_edit);
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    transaction.addToBackStack(null);
    transaction.add(android.R.id.content, new MyFragment());
    transaction.commit();
}

And here's the code to open Fragment B

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    transaction.add(android.R.id.content, new MyOtherFragment());
    transaction.commit();
like image 969
Ollie C Avatar asked Jan 26 '12 16:01

Ollie C


People also ask

What is the purpose of addToBackStack () while commiting fragment transaction?

By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button.

Which piece of code handles the back navigation of the fragments?

Activity onBackPressed() If you are using onBackPressed() to handle Back button events, we recommend using a OnBackPressedCallback instead.

How do you identify a fragment tag?

findFragmentById(R. id. fragment_container); Alternatively, you can assign a unique tag to a fragment and get a reference using findFragmentByTag() .


1 Answers

Have you tried transaction.replace(...) instead of transaction.add(...)? That should work. I'm guessing because if you're just adding a fragment over another, it doesn't see transaction as wanting to go back fro Fragment A.

EDIT The actual answer for the question is below in the comments: addToBackStack() should be used on the fragment which is replacing, not the one being replaced.

like image 118
Alex Curran Avatar answered Nov 15 '22 19:11

Alex Curran