編輯:關於 Android 程式設計
Android 為開發者準備了大量現成的 UI 元件——TextView、Button、ImageView,再加上 LinearLayout、RelativeLayout 這些布局容器,用它們拼出的介面往往已經足夠漂亮。但在真實專案裡,設計稿常常不按套路出牌:一個造型特殊的圓角頭像、一組自家產品獨有的圖表、一個帶呼吸效果的按鈕。這時候與其層層嵌套硬湊,不如自己動手寫一個 View。
想寫好自定義 View,先得弄清楚它站在怎樣的繼承體系裡,以及系統究竟是如何把它一步步畫到螢幕上的。
Android 中所有可見的介面元素,本質上都是 View 與 ViewGroup 構成的樹形結構。View 負責在螢幕上繪製可與使用者互動的內容;ViewGroup 則充當容器,裝下其他 View(也可以是另一個 ViewGroup),一層層嵌套出完整畫面。
系統提供的各類子類,已經覆蓋了常用輸入元件與主流布局方式。而自定義 View,就是要在這棵既有的樹上,長出屬於自己的一枝。

一個 View 從被建立到真正呈現在使用者眼前,會依序走過下面幾步:
走完 onDraw 之後並不是終點,而是一個閉環:只要 View 的內部狀態改變並呼叫 invalidate(),流程便會重新開始,畫面隨之刷新。所有自定義動畫的原理,都在這一行呼叫裡。
一句話記住主線:Constructor → onMeasure → onSizeChanged → onLayout → onDraw,狀態變化時經由 invalidate 回到重繪。
自定義 View 通常要重寫三個建構函數,其中帶 AttributeSet 的那個最為關鍵——XML 裡寫下的屬性,就是從這裡送進來的。
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
接著在 res/values 目錄下建立 attrs.xml,用 declare-styleable 宣告一組屬於自己的屬性:
<resources>
<declare-styleable name="CircleImageView">
<attr name="border_color" format="color" />
<attr name="border_width" format="dimension" />
</declare-styleable>
</resources>
使用前,記得在布局檔的根節點宣告命名空間:
xmlns:app="https://schemas.android.com/apk/res-auto"
於是就能在 XML 裡像使用系統屬性一樣使用它們:
<com.bm.dylan.view.CircleImageView
android:id="@+id/civ_personal_information_head"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="@mipmap/personalcenter_head"
app:border_color="@color/white"
app:border_width="2dp" />
最後在建構函數中用 TypedArray 把值取出來。這裡有個容易忽略的細節:用完記得呼叫 recycle(),否則會造成資源不必要的佔用。
public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.CircleImageView, defStyle, 0);
int borderWidth = a.getDimensionPixelSize(
R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);
int borderColor = a.getColor(
R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR);
a.recycle();
}
format 支援的型別相當豐富,常用的有以下幾種:
| 型別 | format 值 | XML 中的寫法示例 |
|---|---|---|
| 資源引用 | reference | app:name="@string/label" |
| 顏色 | color | app:textColor="#ff0000" |
| 布林值 | boolean | app:isVisible="false" |
| 尺寸 | dimension | app:myWidth="100dp" |
| 浮點數 | float | app:fromAlpha="0.3" |
| 整數 | integer | app:framesCount="22" |
| 字串 | string | app:title="我的標題" |
| 百分比 | fraction | app:pivotX="200%" |
| 列舉 | enum | app:borderRadius="circle" |
| 位運算 | flag | android:windowSoftInputMode="stateUnspecified|adjustPan" |
| 混合型別 | color | app:background="@drawable/bg|#00FF00" |


onMeasure 的兩個參數看起來像是寬和高,其實並不是。它們是由「尺寸」與「測量模式」打包而成的 32 位整數,需要透過 MeasureSpec 拆開來讀。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int w = getMeasureWidth(widthMeasureSpec);
int h = getMeasureHeight(heightMeasureSpec);
// 必須呼叫,否則會拋出異常
setMeasuredDimension(w, h);
}
private int getMeasureWidth(int widthMeasureSpec) {
int result = 0;
int size = MeasureSpec.getSize(widthMeasureSpec);
int mode = MeasureSpec.getMode(widthMeasureSpec);
if (mode == MeasureSpec.EXACTLY) {
result = size;
} else if (mode == MeasureSpec.AT_MOST) {
result = Math.min(result, size);
} else {
result = (int) paint.measureText("") + getPaddingLeft() + getPaddingRight();
}
return result;
}
三種測量模式的含義如下:
| 模式 | 說明 |
|---|---|
| UNSPECIFIED | 父容器不給任何限制,子 View 想多大就多大,多見於 ScrollView 之類的容器。 |
| EXACTLY | 父容器已經明確指定了尺寸,對應 match_parent 或寫死的 dp 值。 |
| AT_MOST | 子 View 大小不超過上限,上限通常就是父容器可用空間,對應 wrap_content。 |
換句話說,重寫 onMeasure 的最終目的只有一個:算出自己的寬高,並交給 setMeasuredDimension 保存起來。
View 的大小不只取決於自己,還受父容器擺布,因此凡是與最終尺寸相關的初始化,最好都放進系統提供的 onSizeChanged 裡。它有四個參數:新寬、新高、舊寬、舊高。
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// 在這裡計算半徑、中心點等依賴尺寸的數值
}
onLayout 決定的是位置而非大小。單純繼承 View 時通常不需要關心它,但一旦自己寫 ViewGroup,這一步就必須實作:一般做法是遍歷所有子 View,逐一算出座標,再呼叫 layout 落位。
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int mTotalHeight = 0;
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
int measuredWidth = childView.getMeasuredWidth();
int measureHeight = childView.getMeasuredHeight();
childView.layout(l, mTotalHeight, measuredWidth, mTotalHeight + measureHeight);
mTotalHeight += measureHeight;
}
}
四個參數分別對應一組取用方法:l 是左側距父容器左緣的距離(getLeft)、t 是頂部距離(getTop)、r 是右側距離(getRight)、b 是底部距離(getBottom)。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 剩下的交給 Canvas
}
Canvas 是畫布,負責「畫什麼形狀」;Paint 是畫筆,負責「用什麼樣式畫」。兩者搭配,幾乎能畫出任何東西。
Canvas 的常用繪製方法:
canvas.drawLine(startX, startY, stopX, stopY, paint); // 直線 canvas.drawRect(left, top, right, bottom, paint); // 矩形 canvas.drawCircle(cx, cy, radius, paint); // 圓形 canvas.drawText(text, x, y, paint); // 文字 canvas.drawBitmap(bitmap, left, top, paint); // 圖片 canvas.drawArc(rectF, startAngle, sweepAngle, useCenter, paint); // 弧線
Paint 的常用屬性設定:
setAntiAlias(true); // 抗鋸齒 setColor(color); // 顏色 setARGB(a, r, g, b); // 分別指定四通道 setAlpha(alpha); // 透明度 setTextSize(size); // 字級 setStyle(Paint.Style.FILL); // 空心或實心 setStrokeWidth(width); // 描邊寬度
自定義 View 寫完之後,通常還需要一組對外方法,讓外部能控制它的狀態,或者反过来通知外部發生了什麼。Button 的點擊事件就是這個思路:內部攔截手勢,外部註冊監聽。自定義 View 也一樣,開一個 setProgress()、setStyle(),或者定義一個 OnXxxListener 介面,元件才真正好用。
三種流派沒有高下之分,只有合不合適。多數時候,能從第一種解決的問題,就不必動用第三種。
Android 5.0 之 NavigationView 使用詳解
側滑導航菜單的實現方式五花八門,網上也不乏各種炫酷方案。這一篇只想安靜地講清楚一件事:Google 在 Android 5.0 之後官方推出的 NavigationVie
Android 實用調試技巧:從 Log API 到 Android Studio 進階斷點
上一篇談的是 UI 優化:include、merge、ViewStub 如何精簡佈局並改善繪製流程、過度繪製的成因與改善方式,以及幾個實用的小 tips。這篇換個主題,談
Android 底部導航實作:使用 ViewPager 與 Fragment
Android 底部導航可用多種方式實作,例如 TabActivity、Fragment、ViewGroup 或 ViewPager。其中 ViewPager 搭配 Fr
手動快取 Retrofit+OkHttp 響應體的實踐
緣起 上一篇部落格只是簡單談了 OkHttp 的快取問題——主要是透過 HTTP 協議裡的 control-cache 來控制快取,而且僅限 Get 請求。若是 Post