Android 按需加載視圖

2018-08-02 18:26 更新

編寫:allenlsy - 原文:http://developer.android.com/training/improving-layouts/loading-ondemand.html

有時(shí)你的 Layout 會(huì)用到不怎么重用的復(fù)雜視圖。不管它是列表項(xiàng) 細(xì)節(jié),進(jìn)度顯示器,或是撤銷時(shí)的提示信息,你可以僅在需要的時(shí)候載入它們,提高 UI 渲染速度。

定義 ViewStub

ViewStub 是一個(gè)輕量的視圖,不需要大小信息,也不會(huì)在被加入的 Layout 中繪制任何東西。每個(gè) ViewStub 只需要設(shè)置 android:layout 屬性來(lái)指定需要被 inflate 的 Layout 類型。

以下 ViewStub 是一個(gè)半透明的進(jìn)度條覆蓋層。功能上講,它應(yīng)該只在新的數(shù)據(jù)項(xiàng)被導(dǎo)入到應(yīng)用程序時(shí)可見。

<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" />

載入 ViewStub Layout

當(dāng)你要載入用 ViewStub 聲明的 Layout 時(shí),要么用 setVisibility(View.VISIBLE) 設(shè)置它的可見性,要么調(diào)用其 inflate() 方法。

((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
// or
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();

Notesinflate() 方法會(huì)在渲染完成后返回被 inflate 的視圖,所以如果你需要和這個(gè) Layout 交互的話, 你不需要再調(diào)用 findViewById() 去查找這個(gè)元素,。

一旦 ViewStub 可見或是被 inflate 了,ViewStub 就不再繼續(xù)存在View的層級(jí)機(jī)構(gòu)中了。取而代之的是被 inflate 的 Layout,其 id 是 ViewStub 上的 android:inflatedId 屬性。(ViewStub 的 android:id 屬性僅在 ViewStub 可見以前可用)

Notes:ViewStub 的一個(gè)缺陷是,它目前不支持使用 <merge/> 標(biāo)簽的 Layout 。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)