尽管 Android 通过各种微件来提供可重复使用的小型互动元素,但您可能还需要重复使用需要特殊布局的大型组件。为了高效地重复使用完整的布局,您可以使用 和 标记在当前布局中嵌入其他布局。
重复使用布局是一项特别强大的功能,因为它允许您创建可重复使用的复杂布局。例如,“是/否”按钮面板,或包含说明文本的自定义进度条。这也意味着您可以单独提取、管理多个布局中的任何常见应用元素,然后将其添加到各个布局中。因此,尽管您可以通过编写自定义
创建可重复使用的布局
如果您已经知道您想要重复使用的布局是什么样,请创建一个新的 XML 文件并定义该布局。例如,下面的布局定义了要添加到每个 Activity 中的标题栏 (titlebar.xml):
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" >
android:layout_height="wrap_content"
android:src="@drawable/gafricalogo" />
根
注意:上述 XML 中的 tools:showIn 属性是一个特殊属性,系统会在编译过程中将其移除,并且仅在设计时在 Android Studio 中使用它;它指定了包含此文件的布局,以便您可以按它嵌入到父级布局中时的显示效果来预览(和修改)此文件。
使用 标记
在要添加可重复使用的组件的布局中,添加 标记。例如,下面的布局包含上述标题栏:
下面是布局文件:
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/app_bg"
android:gravity="center_horizontal">
android:layout_height="wrap_content"
android:text="@string/hello"
android:padding="10dp" />
...
通过在 标记中指定所添加布局的根视图的所有布局参数(任何 android:layout_* 属性),您还可以替换这些参数。例如:
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="@layout/title"/>
不过,如果要使用 标记来替换布局属性,您必须同时替换 android:layout_height 和 android:layout_width 才能让其他布局属性生效。
使用 标记
在一个布局中添加另一个布局时, 标记有助于消除视图层次结构中的冗余视图组。例如,如果您的主布局是一个垂直
为了避免包含此类冗余视图组,您可以改用 元素作为可重复使用的布局的根视图。例如:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/add"/>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/delete"/>
现在,当您将此布局添加到其他布局中(使用 标记)时,系统会忽略 元素并直接在布局中放置两个按钮,以代替 标记。
如需详细了解有关该主题的信息,请参阅布局资源。