TooManyEduardos
TooManyEduardos

Reputation: 4444

Android - issues with onBackPressed with Fragments and FragmentActivity

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

  1. Activity (opens next activity from Intent x = new Intent(params); )->
  2. FragmentActivity (onBackPressed gets disabled here. Tabs are also added here and this FragmentActivity has an inner class that implements ActionBar.TabListener to handle the onTabSelected FragmentTransaction.replace) ->
  3. ListFragment (FragmentTransaction does transaction.replace(args).addToBackStack(null).commit();) ->
  4. Fragment (want to use the physical back button here but it doesn’t seem to be enabled)

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

Answers (1)

Illegal Argument
Illegal Argument

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

Related Questions