編輯:Android 開發實例
沿著最近的路線,繼續談 Android 的 UI 開發。這次要介紹的是 ViewStub——一個「惰性加載」的控件。
本文會說明 ViewStub 的常用屬性、方法,以及實作時容易忽略的注意事項,最後用一個 Demo 把它跑起來。
在進入 ViewStub 之前,先理解 <include/> 這個標籤會有幫助。它的作用是把其他布局資源包含進當前的布局文件中。這個概念在多數平台的開發裡都存在,好處很明顯:可以把龐大的界面拆成多個檔案分別維護,提高可讀性與重用性。
ViewStub 是一個無形的、零尺寸的視圖。它在布局階段只佔據一個「位置座標」,並不會真正把內容加載進來;直到程式運行過程中呼叫 inflate() 或將設為可見時,才會把它所指定的布局資源膨脹加載,並在原位置替換掉自己。
換句話說,只要 setVisibility(int) 或 inflate() 沒有被呼叫過,ViewStub 底下的內容就完全不會被解析與配置,因此消耗的資源極少。正因為這個特性,它常被稱為「懶惰的 include」。
很多畫面並不是一進來就需要把所有東西都顯示出來。例如一個「詳細資料」區塊,平時收合,使用者點了展開才需要出現。若用一般的做法把這些控制項直接寫在布局裡,它們在頁面載入時就會被一併解析、配置記憶體,即使使用者從未展開過。
改用 ViewStub,就能把這部分的开銷延後到真正需要的那一刻,讓首次加載速度變快,同時降低記憶體佔用。
ViewStub 需要設定的屬性其實只有兩個,Android 也提供了對應的 getter / setter:
android:inflatedId:重新指定加載後的父布局控制項 ID。android:layout:指定 ViewStub 要加載的布局資源 ID。ViewStub 唯一需要監聽的事件是 ViewStub.OnInflateListener,它在加載完成時觸發,需實作 onInflate() 方法,簽名如下:
onInflate(ViewStub stub, View inflated)
其中 stub 是目前完成膨脹的 ViewStub 物件,inflated 則是被加載進來的 View 視圖。你可以在這個回呼裡對新加載的內容做一些初始化或額外操作。
這一節是 ViewStub 使用上的關鍵,請務必分清楚:
當 inflate() 或 setVisibility() 被呼叫之後,ViewStub 在布局中就被自己指定的 View 實質替換掉了。這帶來一個直接結果:
inflate(),否則會出錯。setVisibility(View.VISIBLE) 或 View.GONE 來控制顯示與隱藏。所以實務上的正確寫法是:第一次顯示用 inflate(),之後所有的顯示/隱藏都改用 setVisibility()。另外別忘了,inflate() 的回傳值是加載後的父布局物件,不是 ViewStub 本身。
下面的例子會用到 <include/> 標籤,並定義一個 ViewStub 用來加載 RatingBar。畫面上提供三個按鈕:動態加載、動態隱藏,以及操作已加載的 RatingBar。
被加載的布局 res/layout/start.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RatingBar
android:id="@+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
主布局代碼:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<!-- 用 include 標籤直接引入一個布局 -->
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="@layout/start" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFCCDD"
android:orientation="vertical" >
<!-- 定義 ViewStub,加載後的父布局 ID 指定為 inflatedStart -->
<ViewStub
android:id="@+id/stub"
android:inflatedId="@+id/inflatedStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout="@layout/start" />
</LinearLayout>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="動態添加布局" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="動態隱藏布局" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="操作StubInflate的控件" />
</LinearLayout>
實現代碼:
package com.bgxt.viewstubdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.view.ViewStub.OnInflateListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button btn1, btn2, btn3;
private ViewStub viewStub;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
btn3 = (Button) findViewById(R.id.btn3);
viewStub = (ViewStub) findViewById(R.id.stub);
viewStub.setOnInflateListener(inflateListener);
btn1.setOnClickListener(click);
btn2.setOnClickListener(click);
btn3.setOnClickListener(click);
}
private OnInflateListener inflateListener = new OnInflateListener() {
@Override
public void onInflate(ViewStub stub, View inflated) {
Toast.makeText(MainActivity.this, "ViewStub is loaded!",
Toast.LENGTH_SHORT).show();
}
};
private View.OnClickListener click = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
try {
// 尚未 inflate 過,直接膨脹加載
LinearLayout layout = (LinearLayout) viewStub.inflate();
RatingBar bar = (RatingBar) layout.findViewById(R.id.ratingBar1);
bar.setNumStars(4);
} catch (Exception e) {
// inflate 報錯代表已經加載過,改用 setVisibility 顯示
viewStub.setVisibility(View.VISIBLE);
}
break;
case R.id.btn2:
// 隱藏(此時 viewStub 已被替換,仍可控制可見性)
viewStub.setVisibility(View.GONE);
break;
case R.id.btn3:
// 操作已被 inflate 的內容:
// 先取得加載後的父布局,再往下找目標控件。
// 若不這樣做,findViewById 可能會撈到 include 標籤引入的那一份
LinearLayout linearLayout =
(LinearLayout) findViewById(R.id.inflatedStart);
RatingBar rBar =
(RatingBar) linearLayout.findViewById(R.id.ratingBar1);
float numStart = rBar.getRating();
numStart++;
if (numStart > 4) {
numStart = 0;
}
rBar.setRating(numStart);
break;
}
}
};
}
btn3 的做法值得多說明一句。因為這個布局裡同時存在 <include> 引入的一份 start.xml,以及 ViewStub 加載出來的另一份 start.xml,兩者內部都有 ratingBar1 這個 ID。若直接用 Activity 層級的 findViewById(),很可能撈到 include 那一份而不是你要的那一份。
解法就是透過 android:inflatedId 指定的父布局(inflatedStart)先定位到正確的容器,再往內查子控制項。這正是 inflatedId 屬性存在的意義。
另外,範例中用 try-catch 來判斷「是否已加載過」只是為了示範方便。在正式專案中,建議自己維護一個 boolean 狀態旗標來記錄,邏輯會比依賴例外流程清楚得多。
ViewStub 的價值在於「把不必要的初始化成本延後」。在一個包含大量控制項、或含有複雜區塊的頁面上,把非首屏必需的內容改用 ViewStub 承載,往往能明顯改善啟動與渲染的流暢度。
使用時只要記住三件事就不容易出錯:
inflate(),之後一律用 setVisibility()。inflatedId 定位父容器再往下找。
Android 自適應背景圖片的正解:NinePatch(.9.png)完整實戰
做 Android UI,幾乎每個人遲早都會撞上同一堵牆:一張背景圖怎麼才能在各種尺寸下都不變形。這篇文章把 NinePatch 從原理、製作到源碼層面的處理流程完整梳理
Android 登入頁面設計:帳密輸入、錯誤提示與嘗試次數控制
登入頁是使用者對一支 App 的第一印象,也是安全防線的第一關。它要做的事看似簡單——收帳號、收密碼、比對——但細節決定成敗:密碼不能被旁人看光、錯誤要講得清楚、盲猜的次
Android MediaPlayer 教學:播放、暫停與快轉的完整實作
Android 提供多種播放音訊與影片的方式,其中最通用的就是 MediaPlayer 類別。它被封裝在系統的媒體播放服務之上,讓你能用幾行程式碼就完成播放控制。 取得播
Android JSON 解析實戰:用 JSONObject 取出你要的欄位
JSON 的全名是 JavaScript Object Notation(JavaScript 物件符號法),它是一種與程式語言無關的輕量級資料交換格式。語法乾淨、可讀性