在布局優化中,Androi的官方提到了這三種布局<include />、<merge />、<ViewStub />,并介紹了這三種布局各有的優勢,下面也是簡單說一下他們的優勢,以及怎麼使用,記下來權當做筆記。
<include />标簽能夠重用布局檔案,簡單的使用如下:
<LinearLayoutxmlns: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="center_horizontal">
<includelayout="@layout/titlebar"/>
<TextViewandroid:layout_width=”match_parent”
android:layout_height="wrap_content"
android:text="@string/hello"
android:padding="10dp"/>
...
</LinearLayout>
1)<include />标簽可以使用單獨的layout屬性,這個也是必須使用的。
3)在include标簽中所有的android:layout_*都是有效的,前提是必須要寫layout_width和layout_height兩個屬性。
View bookmarks_container_2 = findViewById(R.id.bookmarks_favourite);
bookmarks_container_2.findViewById(R.id.bookmarks_list);
<merge/>标簽在UI的結構優化中起着非常重要的作用,它可以删減多餘的層級,優化UI。<merge/>多用于替換FrameLayout或者當一個布局包含另一個時,<merge/>标簽消除視圖層次結構中多餘的視圖組。例如你的主布局檔案是垂直布局,引入了一個垂直布局的include,這是如果include布局使用的LinearLayout就沒意義了,使用的話反而減慢你的UI表現。這時可以使用<merge/>标簽優化。
<mergexmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:layout_width="fill_parent"
android:text="@string/add"/>
android:text="@string/delete"/>
</merge>
<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_gravity="bottom"/>
當你想加載布局時,可以使用下面其中一種方法:
((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
// or
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();
當調用inflate()函數的時候,ViewStub被引用的資源替代,并且傳回引用的view。這樣程式可以直接得到引用的view而不用再次調用函數findViewById()來查找了。
注:ViewStub目前有個缺陷就是還不支援 <merge /> 标簽。
/**
* @author 張興業
* iOS入門群:83702688
* android開發進階群:241395671
*/
參考:
http://developer.android.com/training/improving-layouts/reusing-layouts.html
http://android-developers.blogspot.com/2009/03/android-layout-tricks-3-optimize-by.html
http://developer.android.com/training/improving-layouts/optimizing-layout.html#Lint
http://android-developers.blogspot.com/2009/02/android-layout-tricks-1.html
http://developer.android.com/training/improving-layouts/loading-ondemand.html
本文轉自xyz_lmn51CTO部落格,原文連結:http://blog.51cto.com/xyzlmn/1344216,如需轉載請自行聯系原作者