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/
文章寫得不錯我就原文拿過來了,但願能幫到人家。。。