A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime. When a ViewStub is made visible, or when inflate() is invoked, the layout resource is inflated. The ViewStub then replaces itself in its parent with the inflated View or Views. Therefore, the ViewStub exists in the view hierarchy until setVisibility(int) or inflate() is invoked. The inflated View is added to the ViewStub's parent with the ViewStub's layout parameters. Similarly, you can define/override the inflate View's id by using the ViewStub's inflatedId property. For instance:
The ViewStub thus defined can be found using the id "stub." After inflation of the layout resource "mySubTree," the ViewStub is removed from its parent. The View created by inflating the layout resource "mySubTree" can be found using the id "subTree," specified by the inflatedId property. The inflated View is finally assigned a width of 120dip and a height of 40dip. The preferred way to perform the inflation of the layout resource is the following: ViewStub stub = (ViewStub) findViewById(R.id.stub); View inflated = stub.inflate(); When inflate() is invoked, the ViewStub is replaced by the inflated View and the inflated View is returned. This lets applications get a reference to the inflated View without executing an extra findViewById().
我們用ViewStub來實現(xiàn)視圖的懶加載瑟慈。比如呼渣,當(dāng)我們的應(yīng)用在打開的時候贮聂,有一些視圖是不需要可見的苍息,我們把它們的Visibility屬性設(shè)置為不可見后,在加載視圖時系統(tǒng)還是會把不可見的視圖一同加載蹋砚,一次性加載復(fù)雜的視圖可能會導(dǎo)致應(yīng)用出現(xiàn)卡頓票摇。ViewStub可以解決這個問題奈梳,它是一個“空”控件,視圖加載時并不會真正加載它指定的視圖圣勒,而是到了需要加載的時候由工程師手動加載费变。
如下。
像上面這樣寫圣贸,我們設(shè)定了它的視圖layout屬性挚歧,但這只是制造了一個空殼,這一個空殼允許我們手動的控制它的加載(在這個視圖加載前吁峻,它是不可見的)滑负。
需要注意的是,viewStub控件只需要被加載一次用含,可以通過isInflated()方法判斷是否已經(jīng)加載過矮慕,隨后通過inflate()方法對視圖進(jìn)行加載,用這一個方法后啄骇,viewStub指定的layout就會實現(xiàn)加載變可見痴鳄。加載代碼如下。
viewStub也支持加載時的監(jiān)聽缸夹,以下是對某個viewStub的加載監(jiān)聽操作痪寻。
通過判斷viewStub的parent是否為空,來判斷ViewStub是否已經(jīng)加載虽惭。原因是viewStub一旦加載橡类,viewStub將脫離當(dāng)前的布局,動態(tài)加載出來視圖將會替換它的位置趟妥,所以加載后的viewStub的parent view將為空猫态。