androidUi优化之--通过include标签来重用布局

通过<include/>来重用布局

虽然Android提供了大量的控件来提供小的可重用的交互元素,但你也需要重用更大的元素,急需要一个特定的布局。为了有效重用完整的布局,你可以使用<include>和<merge/>标签来将另一个布局包含到当前的布局中。

重用布局是非常好强大的,它允许你创建复杂的可重用布局。例如,一个yes/no的按钮面板,或是一个有描述文本的进度条。这意味着布局中任意类型的元素都可以被抽取出来单独处理,然后被包含到每一个布局中。因此,你可以通过编写一个定制的View来创建单独的UI元素,更简单的事在布局中重用其他的布局文件。

一.创建一个重用的布局
如果你知道你想要重用一个布局,创建一个XML布局文件(titlebar.xml):
FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width=”match_parent”
    android:layout_height="wrap_content"
    android:background="@color/titlebar_bg">
 
    <ImageViewandroid:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/gafricalogo"/>
</FrameLayout>
你应该确切知道根视图在每一个你想重用的布局中该如何显示。

二.使用<include>标签
在每一个你想重用布局的文件中,使用<include/>标签来进行添加,例如:
<LinearLayoutxmlns: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">
 
    <includelayout="@layout/titlebar"/>
 
    <TextViewandroid:layout_width=”match_parent”
              android:layout_height="wrap_content"
              android:text="@string/hello"
              android:padding="10dp"/>
 
    ...
 
</LinearLayout>

你也可以重写包含文件的所有布局属性:
<includeandroid: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>标签来消除多余的布局层次。
<mergexmlns: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>
假如你在一个布局中包含该布局,系统将会忽略<merge>标签,直接把这两个按钮放置于<include/>标签所处的位置。

原文链接:http://developer.android.com/training/improving-layouts/reusing-layouts.html

你可能感兴趣的:(androidUi优化之--通过include标签来重用布局)