(一)檢查和優化 Layout 層次
程序的每個組件和 Layout 都需要經過初始化、布局和繪制,如果布局嵌套層次過深,就會導致加載操作更為耗時,更嚴重的話還可能導致內存溢出。使用自帶的HierarchyViewer工 能夠從可視化的角度直觀地獲得布局設計結構,幫助優化布局設計。
(二)使用<include> 標簽
當你需要重用到一些比較復雜的組件,如一個 Toolbar 時,你可以使用 <include>標簽來把其他 Layout 嵌入到當前 Layout。
(三)使用<merge> 標簽
<merge> 標簽
<merge> 標簽在你嵌套 Layout 時取消了 UI 層次中冗余的 ViewGroup,如<include>重用布局中,外層 ViewGroup 是一個 LinearLayout。但如果當我們重用該布局時,是插入到另一個 LinearLayout 中的話,就會導致 Layout 冗余,即其實只需要一個便足夠了。
這時,<merge> 標簽就派上用場了,你可以這樣編寫布局:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/add"/>
<Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/delete"/>
</merge>
通過該標簽,可減少層次避免嵌套過深的情況發生。
(四)ViewStub
ViewStub 是一個輕量視圖,不需要大小信息,也不會在被加入的 Layout 中繪制任何東西,當你引入只在特殊情況才顯示的布局,如進度條,出錯信息,提示信息等布局時,就可以使用 ViewStub。
<ViewStub
android:id="@+id/stub_import"
android:inflatedId="@+id/panel_import"
android:layout="@layout/progress_overlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
其中 Android:id 指 ViewStub 的 id,僅在 ViewStub 可見之前使用。
inflatedId 是引入布局的 id。
加載 ViewStub
載入用 ViewStub 聲明的布局有兩種方式:
((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
// or
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();
(五)使用工具對代碼進行 Lint 檢查
Android Studio 可在菜單項 Analyze - Inspect Code,選擇范圍后對代碼進行 Lint 檢查,從檢查結果中可以得到代碼中不規范的編碼,以便開發者進行修正。
本文博客地址:
http://blog.csdn.net/e_Inch_Photo/article/details/60601251