- Activity 1 is visible. Press a button, and Activity 2 opens.
- Activity 2 adds fragment A to itself (and back stack) and it displays fine
- Pressing a button within the fragment transitions to another fragment, B
- Press Back. Nothing happens. Huh? The Back press is seemingly absorbed and not acted upon, the display remains the same.
- 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();
Have you tried
transaction.replace(...)instead oftransaction.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.