如何在另一个片段的布局中使用fragment xml标记



我正在尝试创建一个包含活动中列表片段的三页。所有的页面都是片段(来自v4支持库),但我需要在其中列出片段。当我尝试时,我遇到了一个问题(https://stackoverflow.com/questions/29473626/viewpager-gives-error-if-i-turn-page)然后我做了一些研究,了解到片段中不可能有片段(我指的是xml片段标签不添加动态嵌套的片段)。但例如,在whatsapp的上一次android更新中,有三个页面合一的活动,其中一个有列表片段(聊天列表),所以我想知道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;
}

您可以嵌套有一些限制的片段(根据文档):

  • Android 4.2或更高版本
  • 只能通过编程方式嵌套它们

更新1这样的东西应该做的工作:

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

最新更新