一、include
1、使用示例如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<include layout="@layout/titlebar"/>
<TextView
android:layout_width=”match_parent”
android:layout_height="wrap_content" />
</LinearLayout>
2、優勢:
include 标簽能夠重用布局檔案,提高代碼的複用。
二、merge
1、merge标簽存在的意義是幫助include标簽排除多餘的一層ViewGroup容器,減少view hierarchy的結構,提升UI渲染的性能。include标簽存在着一個不好的地方,可能會導緻産生多餘的布局嵌套。同樣通過一個小demo來說明:
比如項目中有一個公共的登入按鈕布局,如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="登入按鈕" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@android:color/holo_blue_light">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="40dp"
android:hint="請輸入使用者名" />
<include layout="@layout/login" />
</LinearLayout>
看起來沒什麼問題,其實不知不覺中我們多嵌套了一層布局。我們用工具檢視一下此時布局結構:
除去系統布局,我們自己布局最外層是LinearLayout,然後兩個并列布局EditText與LinearLayout,在LinearLayout裡面是Button登入按鈕。
其實這種情況下:在主界面中,标簽的parent ViewGroup與包含的layout根容器ViewGroup是相同的類型,這裡都是LinearLayout,那麼則可以将包含的layout根容器ViewGroup使用标簽代替,進而減少一層ViewGroup的嵌套,提升UI渲染性能。
這裡我們把activity_login.xml修改如下:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="登入按鈕" />
</merge>
2、使用注意點:
- 根布局是FrameLayout且不需要設定background或padding等屬性,可以用merge代替,因為Activity的ContentView父元素就是FrameLayout,是以可以用merge消除隻剩一個
- 因為merge标簽并不是View,是以在通過LayoutInflate.inflate()方法渲染的時候,第二個參數必須指定一個父容器,且第三個參數必須為true,也就是必須為merge下的視圖指定一個父親節點.由于merge不是View是以對merge标簽設定的所有屬性都是無效的。
三、ViewStub
ViewStub标簽最大的優點是當你需要時才會加載,使用他并不會影響UI初始化時的性能。各種不常用的布局想進度條、顯示錯誤消息等可以使用ViewStub标簽,以減少記憶體使用量,加快渲染速度。ViewStub 是一個不可見的,大小為0的View。ViewStub 标簽使用如下:
<ViewStub
android:id="@+id/stub_import"
android:inflatedId="@+id/panel_import"
android:layout="@layout/progress_overlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />