使用合并和包含标记时如何在Java中获取视图?

时间:2018-08-23 15:40:59

标签: android xml merge include

我的活动的布局XML文件中有多个include标签。我不想使用多余的布局,因此使用“合并”创建了可重复使用的布局。

我需要获取布局中的每个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>

activity_main.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>

1 个答案:

答案 0 :(得分:0)

在您发布的代码中,不需要<merge>标签。当您包含的布局具有多个视图而没有根视图时,可以使用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"/>

问题的另一部分是include标签上的属性如何应用于包含的布局。通常,这些属性将应用于所包含布局的根视图,但是(因为您使用的是<merge>),所以没有根视图。因此,这些ID只会放在地板上(除非您从所包含的布局中删除合并标签)。

如果您不想更改任何布局文件,那么查找视图的唯一方法(因为它们都具有相同的ID)将是getChildAt()