通过 重复使用布局

尽管 Android 通过各种 widget 来提供可重复使用的小型互动元素,但您可能还需要重复使用需要特殊布局的大型组件。为了高效地重复使用完整的布局,您可以使用 <include><merge> 标记在当前布局中嵌入其他布局。

重复使用布局是一项特别强大的功能,因为它允许您创建可重复使用的复杂布局。例如,“是/否”按钮面板,或包含说明文本的自定义进度条。这也意味着您可以单独提取、管理多个布局中的任何常见应用元素,然后将其添加到各个布局中。因此,尽管您可以通过编写自定义 View 来创建各个界面组件,但也可以通过重复使用布局文件来更加轻松地达成目标。

创建可重复使用的布局

如果您已经知道您想要重复使用的布局是什么样,请创建一个新的 XML 文件并定义该布局。例如,下面的布局定义了要添加到每个 activity 中的标题栏 (titlebar.xml):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/titlebar_bg"
    tools:showIn="@layout/activity_main" >

    <ImageView android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/gafricalogo" />
</FrameLayout>

View 应该与您希望此布局在其添加到的每个布局中的显示方式完全一致。

注意:上述 XML 中的 tools:showIn 属性是一个特殊属性,系统会在编译过程中将其移除,并且仅在设计时在 Android Studio 中使用它;它指定了包含此文件的布局,以便您可以按它嵌入到父布局中时的显示效果来预览(和修改)此文件。

使用 <include> 标记

在要添加可重复使用的组件的布局中,添加 <include> 标记。例如,下面的布局包含上述标题栏:

下面是布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/app_bg"
    android:gravity="center_horizontal">

    <include layout="@layout/titlebar"/>

    <TextView android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="@string/hello"
              android:padding="10dp" />

    ...

</LinearLayout>

通过在 <include> 标记中指定所添加布局的根视图的所有布局参数(任何 android:layout_* 属性),您还可以替换这些参数。例如:

<include android:id="@+id/news_title"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         layout="@layout/title"/>

不过,如果要使用 <include> 标记来替换布局属性,您必须同时替换 android:layout_heightandroid:layout_width,才能让其他布局属性生效。

使用 <merge> 标记

在一个布局中添加另一个布局时,<merge> 标记有助于消除视图层次结构中的冗余视图组。例如,如果您的主布局是一个垂直 LinearLayout,其中两个连续视图可以在多个布局中重复使用,那么容纳这两个视图的可重复使用布局就需要有自己的根视图。不过,如果使用另一个 LinearLayout 作为可重复使用的布局的根视图,则会导致垂直 LinearLayout 内出现另一个垂直 LinearLayout。嵌套的 LinearLayout 除了会降低界面的性能之外,没有任何实际用处。

为了避免包含此类冗余视图组,您可以改用 <merge> 元素作为可重复使用的布局的根视图。例如:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/add"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/delete"/>

</merge>

现在,当您将此布局添加到其他布局中(使用 <include> 标记)时,系统会忽略 <merge> 元素并直接在布局中放置两个按钮,以代替 <include> 标记。

如需详细了解有关该主题的信息,请参阅布局资源