[英]Add two different fragments to two layouts with the same body tag?
我正在尝试将两个不同的片段添加到我的活动中的两个容器中。 这些容器是我制作的可折叠视图的一部分:
collapsible_view.xml
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/collapsible_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:gravity="center"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/collapsible_body"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
我尝试使用的容器是collapsible_body
。
我想将其中两个视图添加到我的活动布局中,然后在每个collapsible_body
中添加不同的片段。 但是,使用fragmentTransaction.replace(R.id.collapsible_body...)
并没有指定要替换我的两个视图collapsible_body
中的哪一个。
基本上,与这里的问题相同: Fragment - replace container, if id is not unique
您应该将相同的 id 布局包装在父布局中。 然后将第二个容器的 id 设置为不同的 integer。 例如布局文件如下所示:
<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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.