Re-using Layouts with include

来源:互联网 发布:数据分析主要做什么 编辑:程序博客网 时间:2024/06/06 11:56

主任务原文链接:http://docs.eoeandroid.com/training/improving-layouts/reusing-layouts.html

译者:长剑耿介

完成时间:2012年9月1日


'<include/>'重用布局

尽管Android有各种部件提供了小巧、可重用的互动元素(elements),但在某些需要特殊布局中,您可能还需要重用较大的组件。为了有效地重用完整的布局,您可以使用<include/>和<merge/>标签将另一个布局嵌入到当前布局。

重用布局是非常有用的,因为它允许你创建可重复使用的复杂布局。例如,一个是/否按钮面板,或自定义的带说明文字的进度条。这也意味着,多个布局可以被提取,单独管理,然后被放在每个布局中,您的应用程序的任何元素都是同样的。因此,尽管你可以通过编写自定义的View 创建单独的UI组件,但重新使用布局文件可以更容易地做到这一点。


创建一个可重用的布局

如果已经知道你想重用的布局,您可以创建一个新的XML文件,并定义其布局。例如,这里有一个G-肯尼亚代码实验室( the G-Kenya codelab)的布局,其在每个活动中定义了标题栏( titlebar.xml ):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width=”match_parent”    android:layout_height="wrap_content"    android:background="@color/titlebar_bg">     <ImageView android:layout_width="wrap_content"               android:layout_height="wrap_content"                android:src="@drawable/gafricalogo" /></FrameLayout>
View应该被精确地放在你想其显示的每一个布局中。

使用的<include>标记

向您想要添加可重用的组件的布局中添加<include/>标签。例如,这里有一个从G-肯尼亚代码实验室( the G-Kenya codelab)的布局,其中包括从上面的标题栏:

这是其布局文件:

<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/>标签复写(override)所有的布局参数(任何android:layout_*属性)的布局根视图。 例如:

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

使用<merge>标记

当一个布局包含另一个时,<merge />标签可以消除视图层次结构中多余的视图组。例如,如果您的主要的布局是一个垂直的LinearLayout ,其中两个连续的视图可以被重用在多种布局中,然后放置在两个视图中的可重用布局需要其自己的根视图(root view)。但是,使用其他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/>标签。


0 0
原创粉丝点击