gpt4 book ai didi

java - 使用相同的 body 标签将两个不同的 fragment 添加到两个布局中?

转载 作者:行者123 更新时间:2023-12-01 23:11:24 24 4
gpt4 key购买 nike

我正在尝试将两个不同的 fragment 添加到我的 Activity 中的两个容器中。这些容器是我制作的可折叠 View 的一部分:

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

我想将其中两个 View 添加到我的 Activity 布局中,然后在每个 collapsible_body 中添加不同的 fragment 。但是,使用 fragmentTransaction.replace(R.id.collapsible_body...) 不会指定我的两个 View collapsible_body 中的哪一个代替。

基本上,与这里的问题相同:Fragment - replace container, if id is not unique

最佳答案

您应该将相同的 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);

关于java - 使用相同的 body 标签将两个不同的 fragment 添加到两个布局中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58374915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com