編輯:關於 Android 程式設計
之前寫過一篇討論螢幕適配的文章,裡頭提到過一種類似百分比布局的變通做法。但那位方法缺點很明顯:得為每個螢幕密度準備一份 dimen 數值,白白增加大量無用資料,APK 體積也就跟著膨脹。
其實不必這麼麻煩——Google 在 Support Library 中提供了 percent 庫,專門解決這個問題。它位於 SDK 的 extras 目錄下,若找不到,用 SDK Manager 更新到最新版即可。


可以清楚看到,裡面有 FrameLayout 的子類與 RelativeLayout 的子類各一,此外還有一個 Helper 類別。Helper 負責完成百分比的測量工作,並定義了 PercentLayoutParams 介面——若你想自己實作一個百分比布局,就得實作這個介面。
<resources>
<declare-styleable name="PercentLayout_Layout">
</declare-styleable>
</resources>
從命名就能直接猜到用途:寬度與高度各佔的百分比,以及四邊外边距的百分比。屬性值型別為 fraction,也就是小數形式的百分比。這裡順帶釐清一個常見困惑——layout_marginLeft 與 layout_marginStart 的差異。
寫布局時經常看到這幾個長得很像的屬性:MarginStart/MarginLeft、MarginEnd/MarginRight。
依 API 註釋的說法,MarginStart 指的是控制項距離「起始側」View 的間距,MarginLeft 則是距離「左側」View 的間距,MarginEnd 與 MarginRight 同理。
一般情況下起始側就是左邊,但目前仍有語言(如阿拉伯語)是由右而左書寫。Android 4.2 之後 Google 引入了 RTL 布局以更好地支援由右至左的文字呈現,為了在兩種排版方向下都有一致的用戶體驗,官方建議改用 MarginStart 與 MarginEnd 取代 MarginLeft 與 MarginRight。
compile 'com.android.support:percent:22.2.0'
目標如下圖:左側紅色區塊寬佔 30%、高佔 90%;右側寬佔 70%,上下兩塊各佔 45%。

不用百分比布局時,這類需求得靠 LinearLayout 的 weight 湊出來,但 weight 會帶來額外的布局嵌套,也就容易過度繪製。改用百分比之後,完全不必嵌套,直接標上比例即可。
<android.support.percent.PercentRelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 左側:寬 30%,高 100% 但底部外边距 10%,視覺上等於高 90% -->
<View
android:id="@+id/left"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentBottom="true"
android:background="#ff0000"
app:layout_heightPercent="100%"
app:layout_marginBottomPercent="10%"
app:layout_widthPercent="30%" />
<!-- 右上 -->
<View
android:id="@+id/right_top"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentRight="true"
android:background="#00ff00"
app:layout_heightPercent="45%"
app:layout_widthPercent="70%" />
<!-- 右下 -->
<View
android:id="@+id/right_bttom"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#ffff00"
app:layout_heightPercent="45%"
app:layout_marginBottomPercent="10%"
app:layout_widthPercent="70%" />
</android.support.percent.PercentRelativeLayout>
左側那塊刻意沒有直接寫 90%,而是寫成「高 100% 加上底部外边距 10%」,目的是順便示範 marginBottomPercent 的用法。注意寬高都必須先設為 0dp,百分比才有作用空間。
正如一開始看到的,官方只提供了 FrameLayout 與 RelativeLayout 兩個版本,最常用的 LinearLayout 反倒缺席。想要嗎?自己寫一個就是了。
觀察現有兩個百分比布局的程式碼可以歸納出四個必要步驟:繼承原本的布局類別並補齊各個 constructor;宣告一個 PercentLayoutHelper 物件輔助測量;覆寫 onMeasure 與 onLayout;實作一個繼承原本 LayoutParams、同時實作 PercentLayoutHelper.PercentLayoutParams 介面的內部類。
public class PercentLinearLayout extends LinearLayout {
private final PercentLayoutHelper mHelper = new PercentLayoutHelper(this);
public PercentLinearLayout(Context context) {
super(context);
}
public PercentLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PercentLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
這一段仿造現有的兩個百分比布局即可,直接複製改寫,唯一要記住的是必須繼承自 android.widget.LinearLayout.LayoutParams,才能保住 LinearLayout 特有的 orientation、gravity 等屬性。
public static class LayoutParams extends android.widget.LinearLayout.LayoutParams
implements PercentLayoutHelper.PercentLayoutParams {
private PercentLayoutHelper.PercentLayoutInfo mPercentLayoutInfo;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
this.mPercentLayoutInfo = PercentLayoutHelper.getPercentLayoutInfo(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(android.view.ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public PercentLayoutHelper.PercentLayoutInfo getPercentLayoutInfo() {
return this.mPercentLayoutInfo;
}
protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
PercentLayoutHelper.fetchWidthAndHeight(this, a, widthAttr, heightAttr);
}
}
讓 XML 解析階段產生的 LayoutParams 是我們的內部類別:
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new PercentLinearLayout.LayoutParams(this.getContext(), attrs);
}
這兩段同樣不必自己想,直接沿用即可:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
this.mHelper.adjustChildren(widthMeasureSpec, heightMeasureSpec);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (this.mHelper.handleMeasuredStateTooSmall()) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
this.mHelper.restoreOriginalParams();
}
隨手塗鴉一份來測試:

紅色區塊由上而下,高度分別為父容器的 20%、30%、30%,寬度分別為 30%、50%、40%;其中第三塊靠右對齊,右外边距為父容器的 20%,同時上外边距為 10%。看程式碼會更直接:
<cn.edu.zafu.percentlayout.PercentLinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentBottom="true"
android:background="#ff0000"
android:orientation="vertical"
app:layout_heightPercent="50%"
app:layout_marginBottomPercent="10%"
app:layout_widthPercent="100%">
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#ff0ff0"
app:layout_heightPercent="20%"
app:layout_widthPercent="30%" />
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#dedff0"
app:layout_heightPercent="30%"
app:layout_marginLeftPercent="10%"
app:layout_marginTopPercent="10%"
app:layout_widthPercent="50%">
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="right"
android:background="#1254f0"
app:layout_heightPercent="30%"
app:layout_marginRightPercent="20%"
app:layout_marginTopPercent="10%"
app:layout_widthPercent="40%" />
</View>
</cn.edu.zafu.percentlayout.PercentLinearLayout>
百分比布局最大的價值,是把「比例關係」直接寫進布局檔,省掉 weight 所需的額外嵌套層,對扁平化 view 樹、減少過度繪製有實際幫助。特別適合那種區塊比例固定、不隨內容變動的儀表板或首頁版面。
但它並非萬靈丹。百分比是相對父容器的,一旦父容器尺寸隨狀態變動,比例也會跟著漂移;此外它解決的是「比例」,並不解決「密度」——文字大小、點擊區域的舒適度仍須另外處理。因此實務上更完整的做法是:結構比例交給 Percent 布局,間距與字級仍走 dimen 資源並搭配 smallestWidth 限定符,兩者分工而非互相取代。
Android 本地相冊大量圖片查詢優化
需求背景本需求希望做出類似微信的本地相冊圖片選擇器,主要包含兩個功能:進入圖片選擇頁時,快速顯示手機中所有照片,並依時間倒序排列。切換相冊時,列出所有圖片目錄,並顯示每個
RxLifecycle 實踐:優雅管理 Activity 與 Fragment 的生命周期
為什麼需要 RxLifecycle 在使用 RxJava 時,如果訂閱(Subscription)沒有被及時取消,而它又恰好綁定在有生命周期的 Activity 或 Fr
emoji 表情顯示不出來、變成問號或方框?原因與解法
聊天時對方傳來的 emoji 在你這邊卻變成一個小方框,或者乾脆是問號,這種情況相當常見。無論怎麼重刷系統、重裝 App 都沒有用,因為問題根本不在你手機的軟體壞掉了。
Android 遊戲開發:用觸摸屏手勢切換圖片實作
手勢操作不僅在軟體中常見——例如瀏覽器的翻頁、滾動頁面——在 Android 遊戲裡加入手勢更能增添亮點。像是 CAG、PUZ 類型遊戲的關卡選擇、簡單背景移動,都能用手