0

My Android app is using FragmentTabHost and has 4 tabs A,B,C,D. I'm in tab A with fragment A1, and I navigate to 2nd fragment A2 in tab A, then I switch to tab B, and then switch back to Tab A. Now I click back button which will call popBackStack() method, and I got crash saying that IllegalStateException Fragment A1 already added. Can you help? This is the code I used to create tabs in Main Tab Activity,

    mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); 
    mTabHost.addTab(mTabHost.newTabSpec("profile").setIndicator("Profile"),
            ProfileFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("friends").setIndicator("Friends"),
            FriendsFragmentTab.class, null);
    mTabHost.addTab(
            mTabHost.newTabSpec("notifications").setIndicator(
                    "Notifications"), NotificationFragment.class, null);

    mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
        public void onTabChanged(String tabID) {
            mTabHost.clearFocus();
        }
    });

and I used this code to handle back button press, FragmentManager fragmentManager = getSupportFragmentManager();

fragmentManager.popBackStack();

kenvu
  • 343
  • 6
  • 18

1 Answers1

0

It looks like the general answer is, "Make your own back stack." It might depend on what the contents of the fragments on each tab are, but in my case, the contents themselves had child fragments that seem to get in the way of the back stack working properly.

I did some research and found this post, from a member of the Android team: https://stackoverflow.com/a/8888195/91165

Unless your app has a complex navigation flow with a lot of possible back directions, it might almost be easier to just handle the navigation state directly rather than using a stack. (In my case, the stack would only ever have one "correct" back entry -- back from all the child fragments go to a single home fragment. Horizontal navigation wasn't added to the back stack anyway. I thought the built-in back stack would be more efficient, but after seeing this, I don't think so.)

Community
  • 1
  • 1
lilbyrdie
  • 1,887
  • 2
  • 20
  • 24