虽然Android提供了各种小部件来提供小型且可重用的交互元素,但您可能还需要重新使用需要特殊布局的较大组件。为了有效地重新使用完整的布局,可以使用<include/>和<merge/>标签在当前布局中嵌入另一个布局。
重复使用布局非常强大,因为它允许您创建可重用的复杂布局。例如,是/否按钮面板,或带有说明文字的自定义进度栏。这也意味着您的应用程序的任何元素都可以在多个布局中提取,分别管理,然后包含在每个布局中。因此,尽管可以通过编写自定义来创建各个UI组件,View但通过重新使用布局文件,您可以更轻松地完成此任务。
创建一个可重用的布局
如果您已经知道要重新使用的布局,请创建一个新的XML文件并定义布局。例如,以下是定义要包含在每个活动(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应完全按照您希望它出现在添加此布局的每个布局中。
注意:tools:showIn上述XML中 的属性是一个特殊属性,在编译期间会被删除,并且仅在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>
您也可以android:layout_*通过在<include/>标签中指定包含布局的根视图的所有布局参数(任何属性)。例如:
<include android:id="@+id/news_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="@layout/title"/>
但是,如果要使用<include>标签覆盖布局属性,则必须覆盖两者 android:layout_height并使android:layout_width其他布局属性生效。
使用<merge>标签
将<merge />标签包含在另一个布局中时,该标签有助于消除视图层次结构中的冗余视图组。例如,如果您的主布局是LinearLayout可以在多个布局中重新使用两个连续视图的垂直布局,则放置两个视图的可重用布局需要具有其自己的根视图。但是,使用另一个LinearLayout作为可重用布局的根目录会导致垂直LinearLayout内部出现垂直LinearLayout。嵌套LinearLayout 服务没有真正的目的,除了减慢你的UI性能。
为了避免包含这样的冗余视图组,您可以改为使用该 <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/>标签。
有关与此主题相关的更多信息,请参阅 布局资源。
联系我
QQ:94297366
微信打赏:https://pan.baidu.com/s/1dSBXk3eFZu3mAMkw3xu9KQ
公众号推荐: