Fragments in Action Bar tab fragments?

Can you put fragments inside the fragment for a tab in the Action Bar?

I have a Android (3.0/Honeycomb) application with a main activity that has a Action Bar with 3 tabs. The tabs are added in my activity's onCreate() method, and the tab fragments are added/removed with a TabListener. The code is nearly identical to the sample at http://developer.android.com/guide/topics/ui/actionbar.html#Tabs.

The TabListener looks like this:

public class SwapOutTabListener implements ActionBar.TabListener {
    public SwapOutTabListener(Fragment fragment) {
        _fragment = fragment;
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.add(R.id.fragment_container, _fragment, null);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(_fragment);
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // do nothing
    }

    private Fragment _fragment;
}

Two of my tabs are simple fragments, they just contain a single TextView in them, somewhat like this (most attributes removed for clarity):


    

But the fragment for one of my tabs is more complicated, and contains two embedded fragments, kinda like this:


    
    

When the user selects the tab for this fragment, all of the start-up lifecycle methods (onStart(), onResume()) get called for all three fragments (the tab fragment, plus the two embedded fragments).

But when the user then selects another tab, only the tab fragment gets any of the end-of-lifecycle methods (onPause(), onStop(), etc.). The two embedded fragments never get any of these calls and are never shut down.

This causes problems when the tab is re-selected, as the runtime complains of a duplicate fragment ID when loading the tab fragment:

Binary XML file line #7: Duplicate id 0x7f05000a, tag null, or parent id 0x7f050009 with another fragment for ...Fragment_1

Is it my responsibility to remove these embedded fragments when the tab fragment is removed? If so, when, exactly, do I do that?

16
задан Programmer Bruce 28 May 2011 в 22:53
поделиться