<include><merge>标签用法

include和merge标记的作用主要是为了解决layout的重用问题。

比如我们有三四个Activity但是他们都要用到同一个样式的标题栏,虽然我们把一样的代码copy个三四遍也没关系,但实在是太丑了,而且效率太低,如果这个标题栏要改样式,你岂不是要去三四个地方分别改动。

为了解决这个问题,android中有了include和merge标记

 

以下为标题栏的layout文件titlebar.xml 我们将使用Include标记重用这个文件

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

 

那么在那三四个activity中你可以适用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:gravity="center_horizontal">

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

<TextView

  android:layout_width=”match_parent”

  android:layout_height="wrap_content"

  android:text="@string/hello" />

...

</LinearLayout>

 

调用了Include之后,titlebar文件的内容就被完全嵌入到了include所指定的位置。而且你还可以在include中重新更改一些属性的值,比如

<include

  android:id=”@+id/news_title”

  android:layout_width=”match_parent”

  android:layout_height=”match_parent”

  layout="@layout/title"/>

原来layout中的wrap_content属性就被改成了match_parent属性

 

 

再来说一下merge标记

上面的include有一个副作用就是他多套了一层root节点FrameLayout ,使得再构图的时候会多花费一点时间

如果你不能容忍这个的话那你可以试一下merge标记

titlebar2.xml

<merge xmlns:android="http://schemas.android.com/apk/res/android">

  <ImageView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:src="@drawable/gafricalogo" />

</merge>

这样行成的titlebar2文件就少了外层的root节点,merge标记可以直接成为root节点,当titlebar2被include到文件中时,merge标记就会被忽略掉,而直接由里面的ImageView取代原来include的位置。避免了冗余的layout。

 

所以include和merge是配合使用的,不是一个互斥的或者说是平级的关系。

 

再来说一个在使用这两个标签时最容易出现的问题。

经常会有同学在RelativeLayout中使用include标签

但是却发现include进来的控件无法用layout_alignParentBottom="true"之类的标签来调整。这个真的非常恼火。其实解决方法非常简单,只要你在include的时候同时重载下layout_width和layout_height这两个标签就可以了。如果不重载,任何针对include的layout调整都是无效的!

 

总结:

    • 当LayoutInflater遇到<merge/>标签时,它会跳过它,并将<merge />内的元素添加到<merge />的父元素里。 <merge/>只能作为XML布局的根标签使用,只能替换<FrameLayout/> 当Inflate以<merge />开头的布局文件时,必须指定一个父ViewGroup,并且必须设定attachToRoot为true。参看LayoutInflater.inflate(int resource, ViewGroup root, boolean attachToRoot)。
    • include标签内不能设置RelativeLayout属性,如android:layout_alignParentBottom,因为不起作用 include标签内设置id属性后(android:id),其引用的布局layout内的id属性就不起作用了,怀疑是其引用的layout外层包裹了一层include标签或者是覆盖了其内的属性id 如果没有include标签,所有布局代码都写在一个xml文件中,界面会显得很冗余,可读性很差。而且界面加载的时候是按照顺序加载的,前面的布局不能调用其后面的布局id。而采用include后,一个include中可以引用其后的include中的布局id属性
posted @ 2015-03-07 16:17  soaringEveryday  阅读(1782)  评论(0编辑  收藏  举报