首页 > 解决方案 > 使用合并和包含标签时如何在 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>

标签: androidxmlmergeinclude

解决方案


在您发布的代码中,不需要<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().


推荐阅读