1
I’m working on an app for the college where I’m using Fragments for all my screens, for reuse purposes. The problem is that I cannot control the behavior of the back button between the Fragments.
Inside a Fragment, I call another Fragment, but when I press the back button, the first Fragment does not return, but the Activity is terminated. I read that I could add Fragment to the stack that manages the return, but that doesn’t seem possible inside Fragment to Fragment.
The code I searched is this:
FragmentTransaction mFragmentTransaction = getFragmentManager()
.beginTransaction();
....
mFragmentTransaction.addToBackStack(null);
To remove Fragment from stack:
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getFragmentManager().popBackStack();
}
}
I withdrew that reply: https://stackoverflow.com/a/21635594, where the author made explicit that it works between activities. In my case, that I am calling a Fragment inside another Fragment, what would be the most indicated option? I believe that the behavior that I want, briefly, is this:
Activity 1 loads Fragment 1 automatically. Fragment 1 can call Fragment 2 at a given time, when the Fragment 2 is closed (either by button input of the proper Fragment [ok/cancel] as much as per back button of the device) it must return to Fragment 1.
Using this backstack alternative within Fragment 1 is not working? Do you see any errors? At first I see no problem in this solution... Is there any impediment to not delegate this replacement of fragments to the
Activity
? )?– Wakim
Apparently the bugs corrected themselves. In what I posted the question, it worked. I will post my solution soon.
– Renan Lazarotto