I'm working on an application for college in which I'm using fragments for all my screens for reuse issues. The problem is that I can not control the behavior of the back button between fragments.
Within a fragment, I call another fragment, but when I hit the back button, the first fragment does not return, but rather the activity is terminated. I read that I could add the fragment on the stack that manages the back, but that does not seem to be possible within fragment to fragment.
The code I searched for is this:
FragmentTransaction mFragmentTransaction = getFragmentManager()
.beginTransaction();
....
mFragmentTransaction.addToBackStack(null);
To remove the stack fragment:
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getFragmentManager().popBackStack();
}
}
I have removed this response: link , where the author has explicitly stated that it works between activities. In my case, what I'm calling a fragment within another fragment, what would be the most appropriate option? I think the behavior I want, briefly, is this:
Activity 1 loads Fragment 1 automatically. Fragment 1 can Fragment 2 at any given time, when the Fragment 2 is closed (either by the button's own input [ok / cancel] as much as by push button should return to Fragment 1.