include和merge标记的做用主要是为了解决layout的重用问题。 android
好比咱们有三四个Activity可是他们都要用到同一个样式的标题栏,虽然咱们把同样的代码copy个三四遍也不要紧,但实在是太丑了,并且效率过低,若是这个标题栏要改样式,你岂不是要去三四个地方分别改动。 spa
为了解决这个问题,android中有了include和merge标记 code
如下为标题栏的layout文件titlebar.xml 咱们将使用Include标记重用这个文件 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="http://4265337.blog.163.com/blog/@drawable/gafricalogo" /> </FrameLayout>
那么在那三四个activity中你能够适用Include标记 blog
<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中从新更改一些属性的值,好比 string
<include android:id=”@+id/news_title” android:layout_width=”match_parent” android:layout_height=”match_parent” layout="@layout/title"/>
原来layout中的wrap_content属性就被改为了match_parent属性 it
再来讲一下merge标记 io
上面的include有一个反作用就是他多套了一层root节点FrameLayout ,使得再构图的时候会多花费一点时间 class
若是你不能容忍这个的话那你能够试一下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="http://4265337.blog.163.com/blog/@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调整都是无效的!
原文地址:http://4265337.blog.163.com/blog/static/195375820127935731114/
文章写得不错我就原文拿过来了,但愿能帮到人家。。。