編輯:關於 Android 程式設計
關於 Android 自定義 View,網上的文章和視頻很多,鴻洋的系列教程就很值得一讀。本文的打算是結合影音系統源碼,把「如何自定義一個 View」這件事講透。
分析對象選 TextView,配合 Source Insight 這類工具閱讀源碼會順暢很多。如果手邊沒有完整的 Android 源碼,只有 SDK 的 jar 包,其實在 IDE 裡也能直接跳轉查看。
自定義 View 的標準流程可以歸納為四步:
1. 定義自定義屬性;
2. 在構造方法中讀取這些屬性及其值;
3. 重寫 onMeasure();
4. 重寫 onDraw()。
下面結合 TextView 源碼,一步步做出來。
先看 framework 源碼中 attrs.xml 裡 TextView 的聲明:
... ...
由此可見,自定義屬性依賴 <declare-styleable> 標籤,內部每個屬性用 attr 標籤聲明,name 指定屬性名,format 指定屬性類型。
仿照源碼的寫法,我們在 res/values 下建立 attrs.xml(若不存在則手動創建):
自定義屬性就這樣聲明好了,確實不複雜。
還是先看 TextView 怎麼做:
public class TextView extends View implements ViewTreeObserver.OnPreDrawListener {
...
public TextView(Context context) {
this(context, null);
}
public TextView(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.textViewStyle);
}
@SuppressWarnings("deprecation")
public TextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
...
TypedArray a = theme.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.TextViewAppearance, defStyleAttr, defStyleRes);
...
a = theme.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TextView, defStyleAttr, defStyleRes);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case com.android.internal.R.styleable.TextView_editable:
editable = a.getBoolean(attr, editable);
break;
case com.android.internal.R.styleable.TextView_inputMethod:
inputMethod = a.getText(attr);
break;
...
}
}
a.recycle();
...
}
...
}
只摘了關鍵部分,但足以說明問題。
注意這裡有三個構造方法:一參、二參、三參,且一參調二參、二參調三參、三參調父類。重點看三參版本,它做了三件事:
(1)通過 TypedArray 取得自定義屬性集合;
(2)循環從集合中逐一取出屬性值;
(3)最後調用 a.recycle() 釋放 TypedArray。
補充一點:很多文章在講這一步時會寫成下面這種形式:
String text = array.getString(R.styleable.BottomWidget_tv_text); float textSize = array.getDimension(R.styleable.BottomWidget_tv_textSize, 0); int textColor = array.getColor(R.styleable.BottomWidget_tv_textColor, 0); int background = array.getDrawable(R.styleable.BottomWidget_iv_background); array.recycle();
這種寫法本身不算錯,但有個坑:當某個屬性並未在布局中設置時,它會被賦上一個默認值(往往是 0 或 null),這可能引出意料之外的問題。所以更穩妥的做法是像源碼那樣,用循環遍歷索引的方式取值:
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case com.android.internal.R.styleable.TextView_editable:
editable = a.getBoolean(attr, editable);
break;
...
}
}
補充二點:構造方法之間該互相調用還是調父類?源碼的做法是一參調二參、二參調三參、三參調父類。但如果你自定義的 View 是繼承自某個具體控件(例如 Button),建議改成各構造方法分別調用對應的父類構造方法,這樣才能繼承父類的樣式屬性。
總結:繼承自具體控件且需要沿用其樣式時,用 super(...);直接繼承自 View 時,用 this(...) 逐層委託即可。
按上述方式讀取 ourselves 的屬性:
private int firstColor; // 第一種顏色
private int secondeColor; // 第二種顏色
private int progress = 1; // 當前進度
private int firstColorDefault = Color.BLUE;
private int secondColorDefault = Color.RED;
private int progressDefault = 0;
private int splitSize = 5; // 間隔高度
private int mWidth = 100; // 每塊寬度
private int mHeight = 30; // 每塊高度
private final int maxProgress = 10; // 最大進度
private Paint mPaint;
private float stockWidth = 5; // 描邊寬度
private int stockColor = Color.BLACK;
private float left = 0;
private float top = 0;
private float right = 0;
private float bottom = 0;
public AduioView(Context context) {
this(context, null);
}
public AduioView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AduioView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final Resources.Theme theme = context.getTheme();
TypedArray ta = theme.obtainStyledAttributes(attrs, R.styleable.AduioView, defStyleAttr, 0);
int n = ta.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = ta.getIndex(i);
switch (attr) {
case R.styleable.AduioView_firstColor:
firstColor = ta.getColor(attr, firstColorDefault);
break;
case R.styleable.AduioView_secondColor:
secondeColor = ta.getColor(attr, secondColorDefault);
break;
case R.styleable.AduioView_progress:
progress = ta.getInteger(attr, progressDefault);
break;
}
}
ta.recycle();
mPaint = new Paint();
}
屬性拿到手之後,就可以著手測量與繪製了。這裡先寫 onDraw,看看不重寫 onMeasure 會出什麼問題。
先看 TextView 的 onDraw:
@Override
protected void onDraw(Canvas canvas) {
restartMarqueeIfNeeded();
// 先繪製背景
super.onDraw(canvas);
...
final int scrollX = mScrollX;
final int scrollY = mScrollY;
final int right = mRight;
final int left = mLeft;
final int bottom = mBottom;
final int top = mTop;
final boolean isLayoutRtl = isLayoutRtl();
final int offset = getHorizontalOffsetForDrawables();
final int leftOffset = isLayoutRtl ? 0 : offset;
final int rightOffset = isLayoutRtl ? offset : 0;
final Drawables dr = mDrawables;
if (dr != null) {
int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop;
int hspace = right - left - compoundPaddingRight - compoundPaddingLeft;
// 注意:這裡算出的座標同時被 invalidateDrawable() 使用,改動時需同步
if (dr.mShowing[Drawables.LEFT] != null) {
canvas.save();
canvas.translate(scrollX + mPaddingLeft + leftOffset,
scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightLeft) / 2);
dr.mShowing[Drawables.LEFT].draw(canvas);
canvas.restore();
}
...
}
...
}
本質上就是在畫布(Canvas)上用畫筆(Paint)作畫。接著重寫我們自己的 onDraw:
@Override
protected void onDraw(Canvas canvas) {
mPaint.setAntiAlias(true); // 抗鋸齒
mPaint.setColor(stockColor); // 描邊顏色
mPaint.setStrokeWidth(stockWidth);// 描邊寬度
drawOval(canvas);
}
/**
* 繪製圖形
*/
private void drawOval(Canvas canvas) {
left = 0; // 左座標
right = 100; // 右座標
bottom = mHeight;
mPaint.setColor(firstColor);
// 循環計算座標,繪製底層矩形
for (int i = 0; i < maxProgress; i++) {
top = i * (mHeight + splitSize);
bottom = i * (mHeight + splitSize) + mHeight;
canvas.drawRect(left, top, right, bottom, mPaint);
}
mPaint.setColor(secondeColor);
// 循環計算座標,繪製上層矩形
for (int i = 0; i < progress; i++) {
top = mHeight * (maxProgress - i) + (maxProgress - i - 1) * splitSize - mHeight;
bottom = mHeight * (maxProgress - i) + (maxProgress - i - 1) * splitSize;
canvas.drawRect(left, top, right, bottom, mPaint);
}
}
代碼裡都有註釋,配合 Paint 與 Canvas 的基礎知識並不難理解。
然後在布局中引用這個自定義 View。首先要在最外層 ViewGroup 上聲明命名空間:Android Studio 中寫 xmlns:aduio="https://schemas.android.com/apk/res-auto";Eclipse 中則寫 xmlns:aduio="https://schemas.android.com/apk/res/cn.xinxing.customeview",其中 aduio 是命名空間別名,後者是應用包名。
用 Android Studio 的話,還能在這裡直接看到自定義屬性的取值預覽,這也是推薦它的原因之一。

到這兒自定義 View 就算完成了嗎?還沒有——onMeasure() 我們一直沒重寫。此時把布局中的 android:layout_height 改成 wrap_content,並給它加個黑色背景,再跑一次:

是不是很奇怪?改成 wrap_content 之後,高度竟然撐滿了父容器,表現和 match_parent 一模一樣。
翻 View 源碼就能明白原因:View 默認對待 layout_height 的 wrap_content 與 match_parent 處理方式相同,都是填滿父容器;只有寫成具體數值時才按數值呈現。這正是自定義 View 必須重寫 onMeasure 的理由。
先看 TextView 的實現:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
BoringLayout.Metrics boring = UNKNOWN_BORING;
BoringLayout.Metrics hintBoring = UNKNOWN_BORING;
int des = -1;
boolean fromexisting = false;
if (widthMode == MeasureSpec.EXACTLY) {
// 父容器已明確指定尺寸,直接採用
width = widthSize;
} else {
if (mLayout != null && mEllipsize == null) {
des = desired(mLayout);
}
}
...
}
可見套路是:通過 MeasureSpec 取出模式與尺寸,再结合自身的內容特性算出最終的測量值。
我們的實現:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int width;
// EXACTLY:直接使用父容器給定的值
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
width = mWidth; // 否則使用自定義的寬度
// AT_MOST:取測量值與自算值的較小者
if (widthMode == MeasureSpec.AT_MOST) {
width = Math.min(width, widthSize);
}
}
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int height;
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
// 依據內容計算整體高度
height = mHeight * maxProgress + (maxProgress - 1) * splitSize;
if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(height, heightSize);
}
}
// 保存測量結果
setMeasuredDimension(width, height);
}
重寫之後,分別把 android:layout_height 設為 match_parent、wrap_content 與 500dp,可以看到三種寫法的表現都符合預期了:

(上圖為 match_parent 與 wrap_content)

(上圖為 500dp)
至此,一個完整的自定義 View 就誕生了。
總結:自定義 View 的四步——聲明屬性、構造中取屬性、重寫 onMeasure、重寫 onDraw——平時按這個順序推進即可。其中最容易漏掉的是 onMeasure,而它恰恰決定了你的 View 在 wrap_content 下是否還守得住自己的尺寸。
Android BLE 基礎框架使用詳解(ViseBluetooth)
前言 研究了一段時間的藍牙開發後,我發現網上相關資料比較貧乏,不像其他 Android 資料那麼齊全,大部分內容都得從藍牙聯盟 SIG 官網(https://www.bl
Android 界面編程探險(二):AdapterView、進度條、菜單與對話框
一、UI 組件之 AdapterView 及其子類(二) 1. 自動完成文本框 AutoCompleteTextView MultiAutoCompleteTextVie
Android 拍照功能適配踩坑全記錄
拍照功能的實現 Android 上實現拍照有兩條路:一是直接呼叫相機 API 自訂相機,二是用 Intent 叫起系統相機。以下內容都針對第二種方式的適配。 典型的業務場
Android 開發之簡單聊天室:客戶端與服務器通信實戰
1. 使用 ServerSocket 創建 TCP 服務器端 在 Java 中,能接收其他通信實體連接請求的類是 ServerSocket。ServerSocket 對象