我如何在另一个片段的布局中使用片段 xml 标签?

How can i use fragment xml tag in layout for another fragment?

我正在尝试制作一个包含列表片段的三页 activity。所有页面都是片段(来自 v4 支持库),但我需要在其中列出片段。当我尝试遇到问题()时,我做了一些研究并了解到片段中不能有片段(我的意思是 xml 片段标签不添加动态嵌套片段)。但是例如,在 whatsapp 的最后 android 更新中,一个 activity 三页,其中一个有列表片段(聊天列表)所以我想知道 whatsapp 是怎么做到的?谢谢

我的 xml 包含列表片段的布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="17dp"
    android:text="Welcome to newsfeed" />

<Button
    android:id="@+id/nfButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="52dp"
    android:text="@string/signout" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:orientation="vertical" >
        <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swipe_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <fragment
            android:id="@+id/nfListFragment"
            android:name="com.comp.buzz.newsfeed.NFQuestionFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_horizontal"
            tools:layout="@layout/item_question" />
        </android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>

主片段的onCreativeView方法:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_newsfeed, container, false);
        Fragment fragment = new ListFragment();
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.add(R.id.swipe_container, fragment).commit();
    return view;
}

您可以嵌套片段但有一些限制(根据 doc):

  • Android 4.2 或更高
  • 您只能以编程方式嵌套它们

更新 1 像这样的东西应该可以完成工作:

Fragment fragment = new YourFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.swipe_container, fragment).commit();