Reputation: 4444
I have a question/issue with the physical back button on Android. I want to allow the usage of the back button but only from activity #2, which is a fragment and from there on I only want it to allow the back button to return to the previous fragment.
Here’s my layout/workflow:
(#1)Activity -> (#2)FragmentActivity -> (#3)ListFragment -> (#4)Fragment
When the FragmentActivity (#2) does NOT disable the onBackPressed method, pushing the back button anywhere after the fragmentActivity simply returns the app to the Activity (#1) and not the previous fragment.
So the question is, how do I enable the onBackPressed only from FragmentActivity(#2) and to only return to the previous fragment within the same tab?
Thank you.
Upvotes: 0
Views: 929
Reputation: 10358
Not sure this will work but try this:
@Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
Log.d("length out", "" + fm.getBackStackEntryCount());
if (fm.getBackStackEntryCount() > 2) {
//do nothing you are on other fragments according to your work flow
} else {
// you are in your activity two or one so pop the fragment
fm.popBackStack();
}
}
Upvotes: 1