android - 使用合并和包含标签时如何在 Java 中获取视图?
问题描述
我的活动布局 XML 文件中有多个包含标签。我使用“合并”创建了一个可重用的布局,因为我不想要任何冗余的布局。
我需要在我的布局中获取每个 TextView。如果我不使用合并,我知道该怎么做,但是有没有办法使用合并来做到这一点,如果没有,有没有其他方法可以重用 XML 并避免冗余?
代码:layout_reusable.xml:
<merge
xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:id="@+id/my_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="My TextView"/>
</merge>
活动主.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="*.MainActivity">
<include
layout="@layout/layout_reusable"
android:id="@+id/number1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<include
layout="@layout/layout_reusable"
android:id="@+id/number2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<include
layout="@layout/layout_reusable"
android:id="@+id/number3"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
解决方案
在您发布的代码中,不需要<merge>
标签。当您包含的布局有多个没有根视图的视图时,可以使用合并标签。当您包含的布局中只有一个视图时,您可以省略合并标签。
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="My TextView"/>
问题的另一部分是如何将包含标签上的属性应用于包含的布局。通常,这些属性将应用于包含布局的根视图,但是(因为您使用的是<merge>
),所以没有根视图。因此,这些 id 将被丢弃在地板上(除非您从包含的布局中删除合并标签)。
如果您不想更改任何布局文件,那么查找视图的唯一方法(因为它们都具有相同的 id)将是getChildAt()
.
推荐阅读
- java - Spring Boot 和 Spring 集成。问题
- php - 在同一页面上具有文件输入的多个表单
- php - 修改php中关联数组中的空键
- java - java - 如何使用Java Springboot WebFlux中的反应式Cassandra存储库与多个键空间进行交互?
- c# - 在 Lookup<> 中按值查找键
- java - 将本地目录中的zip文件放入java springboot中的列表中
- java - 官方的openjdk镜像和ubuntu+openjdk有什么区别?
- php - 与“<”相关的 ReactJS 和 PHP Fetch 语法错误
- python - 如何查找一个单词是否在文本文件中并将文件名添加到字典中?
- sql - 为不存在的数据概念化 SQL 查询