Android UI 開(kāi)發(fā)中常用的標(biāo)簽和控件include
、 merge
市咆、 ViewStub
汗捡,最終目的便是為了避免過(guò)深的布局層級(jí)虽抄。
Deep layouts - Layouts with too much nesting are bad for performance. The default maximum depth is 10.
<include/>
include
標(biāo)簽是為了解決重復(fù)定義相同布局的問(wèn)題澈驼,在產(chǎn)品設(shè)計(jì)中常出現(xiàn)應(yīng)用多個(gè)界面中一個(gè)模塊需要呈現(xiàn)相同的布局樣式辛燥,對(duì)我來(lái)說(shuō),這就是一個(gè)可重用的布局組件缝其,可以將其使用單獨(dú)的layout抽離购桑,通過(guò)include標(biāo)簽將其添加到對(duì)應(yīng)的布局中。
<merge/>
The <merge /> tag helps eliminate redundant view groups in your view hierarchy when including one layout within another. For example, if your main layout is a vertical LinearLayout in which two consecutive views can be re-used in multiple layouts, then the re-usable layout in which you place the two views requires its own root view. However, using another LinearLayout as the root for the re-usable layout would result in a vertical LinearLayout inside a vertical LinearLayout. The nested LinearLayout serves no real purpose other than to slow down your UI performance.
<merge/>標(biāo)簽可減少include引入重用布局時(shí)的層級(jí)冗余問(wèn)題氏淑。
比如一個(gè)垂直的線性布局,并且復(fù)用的布局也是一個(gè)類似的垂直線性布局硕噩。那么假残,使用<include/>引入重用布局時(shí)會(huì)出現(xiàn)一個(gè) LinearLayout 作為另一個(gè) LinearLayout 的根節(jié)點(diǎn),這相當(dāng)于真?zhèn)€Layout的層級(jí)結(jié)構(gòu)多了一層且沒(méi)有任何意義。此時(shí)可以使用<merge>標(biāo)簽來(lái)替代可重用 Layout的根節(jié)點(diǎn)辉懒。
ViewStub
ViewStub的官方描述是:
ViewStub is a lightweight view with no dimension and doesn’t draw anything or participate in the layout. As such, it's cheap to inflate and cheap to leave in a view hierarchy. Each ViewStub simply needs to include the android:layout attribute to specify the layout to inflate.
ViewStub是一個(gè)不可視且大小為0的視圖阳惹,可以延遲到運(yùn)行時(shí)填充布局資源。當(dāng)ViewStub設(shè)置為visible或調(diào)用inflate()之后眶俩,就會(huì)填充布局資源莹汤,ViewStub便會(huì)被填充的視圖替代。
總結(jié)下來(lái)它具有以下幾個(gè)特性:
- 需主動(dòng)設(shè)置visible或調(diào)用inflate()才會(huì)填充到父布局颠印,要被加載的子布局通過(guò)android:layout屬性來(lái)設(shè)置纲岭。
- 未主動(dòng)設(shè)置時(shí)其默認(rèn)不可見(jiàn),不會(huì)繪制且不占用布局(此時(shí)的不可見(jiàn)與常用的View.setVisibility(View.GONE)有本質(zhì)區(qū)別线罕,它不會(huì)顯示在當(dāng)前布局的整個(gè)層級(jí)結(jié)構(gòu)中)
- 顯示后ViewStub元素不再是View視圖的一部分止潮。它被引用的資源替換掉,根布局的ID即為ViewStub屬性中android:inflatedId指定的ID钞楼。
- ViewStub只能Inflate一次喇闸,之后ViewStub對(duì)象會(huì)被置為空。按句話說(shuō)询件,某個(gè)被ViewStub指定的布局被Inflate后燃乍,就不能夠再通過(guò)ViewStub來(lái)控制它了。所以它不適用于需要按需顯示隱藏的情況宛琅。
- ViewStub只能用來(lái)Inflate一個(gè)布局文件刻蟹,而不是某個(gè)具體的View,當(dāng)然也可以把View寫在某個(gè)布局文件中夯秃。如果想操作一個(gè)具體的view座咆,還是使用visibility屬性。
- VIewStub中不能嵌套merge標(biāo)簽仓洼。
結(jié)語(yǔ)
以上代碼實(shí)現(xiàn)十分基礎(chǔ)介陶,之所以做這個(gè)總結(jié)是因?yàn)樗鼈兪俏以趯?shí)際開(kāi)發(fā)中經(jīng)常使用的,然后通過(guò)自己的理解和[Hierarchy Viewer]層級(jí)圖更直觀的解釋為什么需要這么使用它們色建。