如何添加一个 inline ListFragment?

我有如下的 layout,包含一些 TextView 和 ImageView。下面的代码我想添加一个ListFragment。

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Name: "
        android:id="@+id/textView"
        android:layout_gravity="left|center_vertical" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/name"
        android:layout_toRightOf="@+id/textView"
        android:layout_gravity="left"
        android:text="Large Text" />
...
    <fragment android:id="@+id/list"
        android:layout_below="@id/name"
        class="com.snot.bodyweightworkout.ExerciseListFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

现在我想使用下面的代码添加 ListFragment。但是我想向上面描述的添加。我猜我应该用相同的方法添加,但是在一个container 的布局中我应该使用什么元素呢?

FragmentManager fm = getSupportFragmentManager();
if (fm.findFragmentById(android.R.id.content) == null) {
    ProgramListFragment list = new ProgramListFragment();
    fm.beginTransaction().add(android.R.id.content, list).commit();
}

如何在 inline 中添加?

该回答引用ChatGPT

您可以在您的布局文件中添加一个容器,例如 FrameLayout,并将 ListFragment 添加到该容器中,如下所示:

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

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Name: "
    android:id="@+id/textView"
    android:layout_gravity="left|center_vertical" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/name"
    android:layout_toRightOf="@+id/textView"
    android:layout_gravity="left"
    android:text="Large Text" />
...
<FrameLayout
     android:id="@+id/list_container"
     android:layout_below="@id/name"
     android:layout_width="match_parent"
     android:layout_height="match_parent" />
</RelativeLayout>

然后,在您的代码中添加如下代码:

FragmentManager fm = getSupportFragmentManager();

if (fm.findFragmentById(R.id.list_container) == null) {
    ProgramListFragment list = new ProgramListFragment();
    fm.beginTransaction()
        .add(R.id.list_container, list)
        .commit();
}

这样,您就可以通过使用具有唯一 ID 的容器,而不是 android.R.id.content 来动态添加您的 ListFragment。