天天看点

Android——布局文件复用 include merge

------<a href="http://www.itheima.com" target="_blank" rel="external nofollow" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

1.<include />标签复用布局文件

在需要添加这些布局的地方,使用<include />标签 。

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

也可以在<include />节点中为被添加的布局文件的root View定义特别标识,重写所有layout参数即可(任何 以“android:layout_”为前缀的属性)

<include android:id=”@+id/news_title”  

         android:layout_width=”match_parent”  

         android:layout_height=”match_parent”  

         layout=”@layout/title”/>  

2.使用<merge />标签 系统忽略< merge />节点并且直接添加去  取代<include />节点。

        当在布局文件中复用另外的布局时, <merge />标签能够在布局层次消除多余的视图元素。例如,如果你的

   主布局文件是一个垂直地包含两个View的LinearLayout,该布局能够复用在其他布局中,而对任意包含两个View的

   布局文件都需要一个root View(否则, 编译器会提示错误)。然而,在该可复用性布局中添加一个LinearLayout

   作为root View,将会导致一个垂直的LinearLayout包含另外的垂直LinearLayout。内嵌地LinearLayout只能减缓

   UI效率,其他毫无用处可言

<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="horizontal">  

    <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"/>  

</LinearLayout>  

   为了避免冗余的布局元素,你可以使用<merge />作为复用性布局文件地root View 。例如:

<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 />节点并且直接添加两个Button去

  取代<include />节点。