(一)檢查和優(yōu)化 Layout 層次
程序的每個(gè)組件和 Layout 都需要經(jīng)過(guò)初始化、布局和繪制,如果布局嵌套層次過(guò)深,就會(huì)導(dǎo)致加載操作更為耗時(shí),更嚴(yán)重的話(huà)還可能導(dǎo)致內(nèi)存溢出。使用自帶的HierarchyViewer工 能夠從可視化的角度直觀(guān)地獲得布局設(shè)計(jì)結(jié)構(gòu),幫助優(yōu)化布局設(shè)計(jì)。
(二)使用<include> 標(biāo)簽
當(dāng)你需要重用到一些比較復(fù)雜的組件,如一個(gè) Toolbar 時(shí),你可以使用 <include>標(biāo)簽來(lái)把其他 Layout 嵌入到當(dāng)前 Layout。
(三)使用<merge> 標(biāo)簽
<merge> 標(biāo)簽
<merge> 標(biāo)簽在你嵌套 Layout 時(shí)取消了 UI 層次中冗余的 ViewGroup,如<include>重用布局中,外層 ViewGroup 是一個(gè) LinearLayout。但如果當(dāng)我們重用該布局時(shí),是插入到另一個(gè) LinearLayout 中的話(huà),就會(huì)導(dǎo)致 Layout 冗余,即其實(shí)只需要一個(gè)便足夠了。
這時(shí),<merge> 標(biāo)簽就派上用場(chǎng)了,你可以這樣編寫(xiě)布局:
<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>
通過(guò)該標(biāo)簽,可減少層次避免嵌套過(guò)深的情況發(fā)生。
(四)ViewStub
ViewStub 是一個(gè)輕量視圖,不需要大小信息,也不會(huì)在被加入的 Layout 中繪制任何東西,當(dāng)你引入只在特殊情況才顯示的布局,如進(jìn)度條,出錯(cuò)信息,提示信息等布局時(shí),就可以使用 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 可見(jiàn)之前使用。
inflatedId 是引入布局的 id。
加載 ViewStub
載入用 ViewStub 聲明的布局有兩種方式:
((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
// or
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();
(五)使用工具對(duì)代碼進(jìn)行 Lint 檢查
Android Studio 可在菜單項(xiàng) Analyze - Inspect Code,選擇范圍后對(duì)代碼進(jìn)行 Lint 檢查,從檢查結(jié)果中可以得到代碼中不規(guī)范的編碼,以便開(kāi)發(fā)者進(jìn)行修正。
本文博客地址:
http://blog.csdn.net/e_Inch_Photo/article/details/60601251