編輯:關於 Android 程式設計
談到布局優化,ViewStub 幾乎一定會被提到。但多數人只是知道要「用它」,卻沒看過它究竟如何運作。本文直接從源碼切入。
打開 ViewStub.java 會發現它就是 View 的子類,並附上一段說明:
A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime.
一句話點出三個特性:不可見、零尺寸、可在執行期延遲 inflate。接著看它是怎麼做到這三件事的。
建構時會呼叫 initialize():
private void initialize(Context context) {
mContext = context;
setVisibility(GONE);
setWillNotDraw(true);
}
setVisibility(GONE) 讓它在布局載入時就不佔位、不顯示;setWillNotDraw(true) 則保證它的 onDraw() 不會被執行。
但實際上不止於此。ViewStub 還覆寫了父類的 draw()、dispatchDraw() 與 onMeasure():
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(0, 0);
}
@Override
public void draw(Canvas canvas) {
// 什麼都不做
}
@Override
protected void dispatchDraw(Canvas canvas) {
// 什麼都不做
}
看到這幾行就明白了:它雖然是個 View,卻完全不測量、不繪製, measure 結果直接是 0×0。這才是「不可見且零尺寸」的真正由來——從源頭上把成本降到最低。
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.
說明的重點是:一旦设为 visible 或直接呼叫 inflate(),它所對應的布局才會被載入,而且它會把自己從父容器中替換掉。
public void setVisibility(int visibility) {
if (mInflatedViewRef != null) {
View view = mInflatedViewRef.get();
if (view != null) {
view.setVisibility(visibility);
} else {
throw new IllegalStateException("setVisibility called on un-referenced view");
}
} else {
super.setVisibility(visibility);
if (visibility == VISIBLE || visibility == INVISIBLE) {
inflate();
}
}
}
邏輯很清楚:若 mInflatedViewRef 已有值,代表曾經 inflate 過,那就把可見性轉發給那個被加載出來的 View;若還是 null 且這次要求可見,就呼叫 inflate()。也就是說,設定可見性這件事本身就是觸發加載的開關。
public View inflate() {
final ViewParent viewParent = getParent();
if (viewParent != null && viewParent instanceof ViewGroup) {
if (mLayoutResource != 0) {
final ViewGroup parent = (ViewGroup) viewParent;
LayoutInflater factory = (mInflater != null)
? mInflater : LayoutInflater.from(mContext);
final View view = factory.inflate(mLayoutResource, parent, false);
if (mInflatedId != NO_ID) {
view.setId(mInflatedId);
}
final int index = parent.indexOfChild(this);
parent.removeViewInLayout(this);
final ViewGroup.LayoutParams layoutParams = getLayoutParams();
if (layoutParams != null) {
parent.addView(view, index, layoutParams);
} else {
parent.addView(view, index);
}
mInflatedViewRef = new WeakReference<View>(view);
if (mInflateListener != null) {
mInflateListener.onInflate(this, view);
}
return view;
} else {
throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
}
} else {
throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
}
}
逐行看關鍵動作:記下自己在父容器中的索引 → 把自己移除 → 在同一個位置插入加載出來的新 View,並沿用原本的 LayoutParams → 用 WeakReference 保存結果 → 通知 listener。
「原位替換」是這裡最漂亮的一手:開發者不必操心新 View 該放哪裡,位置資訊由 ViewStub 自己保管。
public ViewStub(Context context, AttributeSet attrs, int defStyle) {
TypedArray a = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.ViewStub, defStyle, 0);
mInflatedId = a.getResourceId(R.styleable.ViewStub_inflatedId, NO_ID);
mLayoutResource = a.getResourceId(R.styleable.ViewStub_layout, 0);
a.recycle();
a = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.View, defStyle, 0);
mID = a.getResourceId(R.styleable.View_id, NO_ID);
a.recycle();
initialize(context);
}
也就是 XML 上的 android:layout 與 android:inflatedId 兩個屬性。前者是稍後要載入的布局,後者可讓加載出來的 View 換一個新的 id,避免與佔位階段的 id 混淆。
ViewStub stub = (ViewStub) findViewById(R.id.stub); View inflated = stub.inflate();
ViewStub 的價值在於「把不確定是否會用到的介面從初始 inflate 中移出去」。典型場景包括:錯誤提示區塊、網路載入失敗的重試畫面、展開式的進階設定、少數條件才顯示的浮層。這些區塊多數使用者一輩子都不會看到,卻在每次進入頁面時被完整解析一次,白白拖慢啟動速度。
反過來說,若某個區塊幾乎一定會顯示,用 ViewStub 反而多了一層延遲與額外呼叫,得不償失。判斷標準很簡單:使用率低於某個門檻、且布局本身有相當複雜度,才值得包成 ViewStub。此外要注意它只能替換一次, inflate 之後 ViewStub 就已從视图樹中消失,無法重複使用。
玩轉 Android Drawable:用 XML 畫出圓角與邊框,並解掉 2.x 的圆角 BUG
很久沒更新部落格,很多東西用完就忘,實在該記下來。除了自己複習,也推薦讀者養成寫筆記的習慣——開發 App 時真正用到的知識遠比一開始想像的多,甚至還會中途被派去用別的語
微信小惱惱一次解決:小影片與全螢幕播放設定
微信小問題可用設定解決。Android版可到設定、通用,把朋友圈小影片設為關閉或僅Wi-Fi,避免浪費行動網路。 Windows Phone看影片無法全屏,可到設定、輔助
Android 6.0 執行期授權機制與權限管理實作
6.0 之後,授權邏輯整個換了 Android 6.0(API 23)對權限系統做了一次結構性的改造。只有當你的 targetSdkVersion 設為 23 以上,且應
帶著疑惑走進 Dagger2:從依賴注入到注解的實戰
Dagger2 最初由 Square 研發,後交由 Google 維護,是一款依賴注入(Dependency Injection,簡稱 DI)框架。它之所以越來越受歡迎,