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();
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.
Activity onBackPressed() If you are using onBackPressed() to handle Back button events, we recommend using a OnBackPressedCallback instead.
findFragmentById(R. id. fragment_container); Alternatively, you can assign a unique tag to a fragment and get a reference using findFragmentByTag() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With