Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 開發技巧:用 ViewStub 實現控制項的惰性載入

編輯:Android 開發實例

前面介紹過 <include> 標籤,它可以在佈局檔中引用另一個佈局檔,並覆蓋被引用佈局根節點所有以 android:layout 開頭的相關屬性。透過 <include>,我們能把龐大的佈局檔拆解成若干較小的檔案,且这些小檔案還能被重複引用,達到重用的目的。

<include> 雖好用,卻有個問題:佈局中的控制項未必在程式啟動時全都用得上,有些只在特定情境才會用到。舉例來說,一款看書軟體只有在下載電子書時才需要顯示進度條,平時閱讀的都是本機電子書,根本用不到進度條,因此啟動時完全可以先不載入它。但用 <include> 引用這個含進度條的佈局時,它會不問三七二十一地把所有控制項一股腦兒載入記憶體。或許有人覺得一個進度條佔不了多少資源,全都載入也無妨——這說法也許沒錯,但若載入的不是進度條,而是大量顯示大圖的 ImageView,還分散在多處載入,那恐怕很快就會把可憐的手機資源耗盡。因此,我們急需一種機制來改變 <include> 的這種行為,做到「只在需要時才載入」,這正是本文要介紹的 ViewStub 控制項。

ViewStub 是不可視的控制項,作用與 <include> 基本相同,同樣是在佈局檔中用 <ViewStub> 標籤引用其他佈局檔。兩者唯一的差別在於,ViewStub 不會馬上載入被引用的佈局,只有在呼叫 ViewStub.inflate 或 ViewStub.setVisibility(View.VISIBLE) 之後,才會真正載入引用的控制項。先來看兩個佈局檔。

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="我的按鈕"
android:onClick="onClick_Button"/>
<include layout="@layout/custom"/>
</LinearLayout>

custom.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="按鈕1"/>
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="按鈕2"/>
</LinearLayout>

main.xml 用 <include> 引用 custom.xml 時,螢幕上會立刻顯示三個按鈕(如圖 5.56)。若把 <include> 換成下面的寫法,程式啟動時就只會顯示 main.xml 中定義的那顆按鈕(如圖 5.57)。

<ViewStub android:id="@+id/viewstub" android:inflatedId="@+id/button_layout"
android:layout="@layout/custom" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>


              圖5.56  使用<include>標簽裝載控件


圖5.56使用<ViewStub>標簽裝載控件

使用 <ViewStub> 引用佈局後,還需呼叫 ViewStub.inflate 或 ViewStub.setVisibility(View.VISIBLE) 才會載入所引用的控制項,代碼如下:

public void onClick_Button(View v)
{
//ViesStub控件只能獲得一次,第二次再使用findViewById獲得該ViewStub對象,則返回null
View view = findViewById(R.id.viewstub);
if (view != null)
{
//或調用ViewStub.inflate方法
//view = ((ViewStub)view).inflate();
//裝載ViewStub引用的custom.xml文件中的控件
((ViewStub)view).setVisibility(View.VISIBLE);
}
else
{
setTitle("view is null");
}
}

單擊「我的按鈕」後,會顯示 custom.xml 中定義的兩個按鈕,效果與圖 5.56 完全相同。

注意:<ViewStub> 與 <include> 一樣,也能設定所引用佈局根節點所有與佈局相關的屬性。不同的是,<include> 的 android:id 會直接覆蓋被引用佈局根節點的 android:id,而 <ViewStub> 的 android:id 則如同一般控制項,用於在程式碼中引用該控制項;在 <ViewStub> 中需要用 android:inflatedId 來覆蓋被引用佈局根節點的 android:id。雖然 <ViewStub> 幾乎可完全取代 <include>,但唯一的不足是它目前還無法取代 <merge>。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved