片段-如果ID不唯一,请替换容器 [英] Fragment - replace container, if id is not unique
问题描述
我有一个布局,其中有两个具有相同ID的视图.如果要查找视图,只需调用parentView1.findViewById(R.id.content)
或parentView2.findViewById(R.id.content)
即可获取正确的视图.
I have a layout that has two views with the same id. If I want to find the view I just call parentView1.findViewById(R.id.content)
or parentView2.findViewById(R.id.content)
to get the correct view.
如果我想用一个片段替换一个容器,我能以某种方式定义我想要替换的那个容器吗?
If I want to replace a container with a fragment, can I somehow define which one I want to be replaced?
推荐答案
您应将相同的id布局包装在父布局中.然后将第二个容器的ID设置为其他整数.例如,布局文件如下所示:
You should wrap the same id layouts in a parent layout. And then set the id for second container to a different integer. For example layout file would look like this:
<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设置为其他容器.例如:
And you would access them from using parent ids first. Then setting the id for second container to a different one. For example:
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)
Same access logic but in Java (in case you're not using 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);
这篇关于片段-如果ID不唯一,请替换容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!