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开发者_JAVA百科 for clarity):
<LinearLayout>
<TextView android:text="Tab 1" />
</LinearLayout>
But the fragment for one of my tabs is more complicated, and contains two embedded fragments, kinda like this:
<LinearLayout>
<fragment
android:name="...Fragment_1"
android:id="@+id/frag1"
/>
<fragment
android:name="...Fragment_2"
android:id="@+id/frag2"
/>
</LinearLayout>
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?
No, fragments are currently not in a hierarchy. I looked at doing this, but at this point all of the use cases for it have been driven mostly by an extreme over-use of fragments where each separate UI element is implement as a fragment. That isn't how they are intended to be used, they are intended to encapsulate the major top-level pieces of an application. If you have a hierarchy of stuff, that is what your layout and views are for.
Ahhhh. The feeling of realization. I just found this - "Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically."
http://developer.android.com/about/versions/android-4.2.html#NestedFragments
精彩评论