布局優(yōu)化的時(shí)候經(jīng)常用到的三種方式
-
include
-
merge
-
ViewStub
1桦卒、<include />標(biāo)簽重用布局
include標(biāo)簽?zāi)軌蛑赜靡讯x好的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/id_text_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<include
android:id="@+id/id_text_2"
layout="@layout/layout_1"
android:layout_width="match_parent"
android:layout_height="0"
android:layout_weight="0.5"/>
</LinearLayout>
重用的布局layout_1
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/id_reuse_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<include layout="@layout/嵌套的其他重用布局"/>
</LinearLayout>
1)必須聲明一個(gè)layout屬性,值為重用的布局
2)可以聲明其他屬性屑宠,include中聲明的id會(huì)覆蓋重用布局中的id
eg:上面的代碼中id_text_2會(huì)覆蓋id_reuse_layout
3)可以使用全部的android:layout_*屬性,必須聲明android:layout_width和android:layout_height屬性
eg:上面的布局中weight生效的前提是width和height屬性必須聲明
4)可以嵌套使用
2、<merge />標(biāo)簽減少視圖層級(jí)
<merge/>標(biāo)簽在UI的結(jié)構(gòu)優(yōu)化中起著非常重要的作用,它可以刪減多余的層級(jí)呀闻,優(yōu)化UI。<merge/>多用于替換當(dāng)一個(gè)布局包含另一個(gè)布局時(shí)萍启,<merge/>標(biāo)簽消除視圖層次結(jié)構(gòu)中多余的層級(jí)。例如你的主布局文件是垂直布局屏鳍,引入了一個(gè)垂直布局的include勘纯,這是如果include布局使用的LinearLayout就沒(méi)意義了,使用的話反而減慢你的UI表現(xiàn)钓瞭。這時(shí)可以使用<merge/>標(biāo)簽優(yōu)化驳遵。
<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>
現(xiàn)在添加該布局時(shí)(使用<include />標(biāo)簽),系統(tǒng)忽略<merge />層并且直接添加兩個(gè)Button到你的布局中山涡。
3堤结、<ViewStub />標(biāo)簽占位
<ViewStub />標(biāo)簽最大的優(yōu)點(diǎn)是當(dāng)你需要時(shí)才會(huì)加載,使用他并不會(huì)影響UI初始化時(shí)的性能鸭丛。各種不常用的布局想進(jìn)度條竞穷、顯示錯(cuò)誤消息等可以使用<ViewStub />標(biāo)簽,以減少內(nèi)存使用量鳞溉,加快渲染速度瘾带。<ViewStub />是一個(gè)不可見(jiàn)的,大小為0的View熟菲。
<ViewStub
android:id="@+id/stub_import"
android:layout="@layout/progress_overlay"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
當(dāng)你想加載布局時(shí)看政,可以使用下面其中一種方法:
((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
// or
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();