您应该将相同的 id 布局包装在父布局中。然后将第二个容器的 id 设置为不同的整数。例如布局文件如下所示:
<LinearLayout
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"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/parent_one">
<include layout="@layout/container" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/parent_two">
<include layout="@layout/container"/>
</LinearLayout>
</LinearLayout>
您将首先使用父 ID 访问它们。然后将第二个容器的 id 设置为不同的。例如:
val containerOneId = parent_one.container.id
val containerTwoId = 1
parent_two.container.id = containerTwoId
openFragment(TestFragment().apply {
val b = Bundle()
b.putString(TestFragment.ARG, "Fragment one")
arguments = b
}, containerOneId)
openFragment(TestFragment().apply {
val b = Bundle()
b.putString(TestFragment.ARG, "Fragment two")
arguments = b
}, containerTwoId)
相同的访问逻辑,但在 Java 中(如果您不使用 Kotlin)
LinearLayout parentOne = (LinearLayout) findViewById(R.id.parent_one);
LinearLayout parentTwo = (LinearLayout) findViewById(R.id.parent_two);
FrameLayout containerOne = parentOne.findViewById(R.id.container);
FrameLayout containerTwo = parentTwo.findViewById(R.id.container);
int containerOneId = containerOne.getId();
int containerTwoId = 1;
containerTwo.setId(containerTwoId);
openFragment(new TestFragment(), containerOneId);
openFragment(new TestFragment(), containerTwoId);