編輯:關於 Android 程式設計
自定義 View 一直是我的短板,趁著公司專案相對空閒的這段時間,我決定集中補強這方面。這個系列主要記錄我在自定義 View 學習路上的心得與踩坑經驗。
某天刷微博時,注意到「微博運動」頁面裡運動積分的呈現有一個相當細膩的動畫:數字往上跳,外圈圓弧也跟著長出來。既然看到了,就拿它當作自定義 View 之路的第一站。

分數的顏色與字號、外圓的顏色、圓弧的顏色都支援自訂,整體觀感與微博那版相當接近。下面按步驟拆解實現過程。
在 res/values/ 下建立 attrs.xml,先定義公共屬性,再用 declare-styleable 把它們組合成一個樣式集:
<?xml version="1.0" encoding="utf-8"?>
<resources>
//自定義屬性名,定義公共屬性
<attr name="titleSize" format="dimension"></attr>
<attr name="titleColor" format="color"></attr>
<attr name="outCircleColor" format="color"></attr>
<attr name="inCircleColor" format="color"></attr>
<attr name="lineColor" format="color"></attr>
//自定義控件的主題樣式
<declare-styleable name="MySportView">
<attr name="titleSize"></attr>
<attr name="titleColor"></attr>
<attr name="outCircleColor"></attr>
<attr name="inCircleColor"></attr>
</declare-styleable>
</resources>
這裡依序定義了字型大小、字型顏色、外圓顏色、圓弧顏色四個屬性,format 用來指定該屬性的取值型別。
接著在佈局檔中宣告我們的 View,別忘了先引入自訂命名空間 xmlns:app="https://schemas.android.com/apk/res-auto":
<com.example.tangyangkai.myview.MySportView
android:id="@+id/sport_view"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_margin="20dp"
app:inCircleColor="@color/strong"
app:outCircleColor="@color/colorAccent"
app:titleColor="@color/colorPrimary"
app:titleSize="50dp" />
/**
* Created by tangyangkai on 16/5/23.
*/
public class MySportView extends View {
private String text;
private int textColor;
private int textSize;
private int outCircleColor;
private int inCircleColor;
private Paint mPaint, circlePaint;
//繪製文本的範圍
private Rect mBound;
private RectF circleRect;
private float mCurrentAngle;
private float mStartSweepValue;
private int mCurrentPercent, mTargetPercent;
public MySportView(Context context) {
this(context, null);
}
public MySportView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MySportView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//獲取我們自定義的樣式屬性
TypedArray array = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.MySportView, defStyleAttr, 0);
int n = array.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = array.getIndex(i);
switch (attr) {
case R.styleable.MySportView_titleColor:
//默認顏色設置為黑色
textColor = array.getColor(attr, Color.BLACK);
break;
case R.styleable.MySportView_titleSize:
//默認設置為16sp,TypedValue也可以把sp轉化為px
textSize = array.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
break;
case R.styleable.MySportView_outCircleColor:
outCircleColor = array.getColor(attr, Color.BLACK);
break;
case R.styleable.MySportView_inCircleColor:
inCircleColor = array.getColor(attr, Color.BLACK);
break;
}
}
array.recycle();
init();
}
//初始化
private void init() {
mPaint = new Paint();
circlePaint = new Paint();
//設置是否抗鋸齒
mPaint.setAntiAlias(true);
//圓環開始角度(-90° 為 12 點鐘方向)
mStartSweepValue = -90;
mCurrentAngle = 0;
mCurrentPercent = 0;
mBound = new Rect();
}
}
自定義 View 通常要實作三個構造方法,它們是一層呼叫一層的遞進關係,因此只要在最後一個(帶 AttributeSet 與 defStyleAttr 的那個)裡讀取屬性即可。
第一步:用 obtainStyledAttributes() 取得自定義樣式陣列。
第二步:遍歷索引,取出對應屬性在 XML 中寫的值。
第三步:循環結束後呼叫 array.recycle() 回收資源。
第四步:完成必要的初始化。這裡要特別提醒:不要把 new 放在 onDraw 裡。onDraw 是極高頻的執行路徑,每次都配置記憶體會造成不必要的效能與記憶體壓力,物件應在構造階段一次建立好。
若不重寫 onMeasure,系統會走預設邏輯:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
這個方法負責測量控制項尺寸。Android 加載佈局時,子 View 會把自己需要多大空間回報給父容器,父容器再決定實際分配。其中 MeasureSpec 的三種模式分別是:
EXACTLY:父容器要求子 View 必須是 specSize 指定的大小,對應明確數值或 match_parent。
AT_MOST:子 View 最大只能是 specSize,通常對應 wrap_content。
UNSPECIFIED:父容器不施加任何限制,子 View 想要多大就多大,實務上很少用到。
那麼 wrap_content 的效果該怎麼處理?只能自己重寫 onMeasure:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//布局裡設置了固定值時,直接取該值;否則按內容計算
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
mPaint.setTextSize(textSize);
mPaint.getTextBounds(text, 0, text.length(), mBound);
float textWidth = mBound.width();
width = (int) (getPaddingLeft() + textWidth + getPaddingRight());
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
mPaint.setTextSize(textSize);
mPaint.getTextBounds(text, 0, text.length(), mBound);
float textHeight = mBound.height();
height = (int) (getPaddingTop() + textHeight + getPaddingBottom());
}
//調用父類方法,把 View 的大小告訴父佈局
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
//設置外圓的顏色
mPaint.setColor(outCircleColor);
//設置外圓為空心
mPaint.setStyle(Paint.Style.STROKE);
//畫外圓
canvas.drawCircle(getWidth() / 2, getWidth() / 2, getWidth() / 2, mPaint);
//設置字體顏色與大小
mPaint.setColor(textColor);
mPaint.setTextSize(textSize);
//得到字體的寬高範圍
text = String.valueOf(mCurrentPercent);
mPaint.getTextBounds(text, 0, text.length(), mBound);
//繪製居中文字
canvas.drawText(text, getWidth() / 2 - mBound.width() / 2,
getWidth() / 2 + mBound.height() / 2, mPaint);
//繪製單位「分」
mPaint.setTextSize(textSize / 3);
canvas.drawText("分", getWidth() * 3 / 4, getWidth() / 3, mPaint);
circlePaint.setAntiAlias(true);
circlePaint.setStyle(Paint.Style.STROKE);
//設置圓弧的寬度
circlePaint.setStrokeWidth(10);
//設置圓弧的顏色
circlePaint.setColor(inCircleColor);
//圓弧範圍
circleRect = new RectF(20, 20, getWidth() - 20, getWidth() - 20);
//繪製圓弧
canvas.drawArc(circleRect, mStartSweepValue, mCurrentAngle, false, circlePaint);
//判斷當前百分比是否小於目標百分比
if (mCurrentPercent < mTargetPercent) {
mCurrentPercent += 1;
//每個百分比對應 3.6 度
mCurrentAngle += 3.6;
//每 100ms 重畫一次
postInvalidateDelayed(100);
}
}
這裡分享一個很實用的小技巧:動手寫 onDraw 之前,先在紙上把座標系、各元素的位置簡單標註一遍,寫起來會順暢很多。

幾個關鍵點對照上圖說明:
(1)drawText 的第二、三個參數就是圖中 A 點的位置,透過 mBound 的寬高做偏移即可讓文字居中:
canvas.drawText(text, getWidth() / 2 - mBound.width() / 2, getWidth() / 2 + mBound.height() / 2, mPaint);
(2)繪製圓弧前要先確定範圍,RectF 的四個參數就是內圓外接正方形的座標:
circleRect = new RectF(20, 20, getWidth() - 20, getWidth() - 20);
(3)drawArc 的參數依序是:圓弧範圍、起始角度、掃描角度、是否連圓心(為 true 時會畫成扇形,這裡取 false)、畫筆:
canvas.drawArc(circleRect, mStartSweepValue, mCurrentAngle, false, circlePaint);
最後是數字遞增與圓弧生長的動畫。核心就是 postInvalidateDelayed():它會在指定延遲後回頭呼叫 invalidate(),進而觸發 onDraw,形成一個循環。只要定義全域的 mCurrentPercent 與 mCurrentAngle,在 onDraw 中持續遞增,動畫自然就出來了。
到這裡,整個自定義 View 就完成了。完整梳理一遍之後會發現,它其實沒有想像中那麼可怕。下一篇自定義 View,我們再見。
布局與控件(四):Button 的兩種事件綁定方式與自訂背景
第 4 節 Button Button 是使用者互動的起點,也是每個 Android 新手都會碰到的第一個「會動」的控件。 從繼承結構看,Button 直接繼承自
Android 開發常見錯誤排查合集(一):簽名、模擬器與 DDMS 問題
Android 開發過程中難免遇到各種奇怪的錯誤訊息。本文整理幾個高頻出現的問題與解法,幫你少走冤枉路。 1. Re-installation failed due t
Android 聊天表情實作:表情輸入、翻頁動效與下拉刷新歷史訊息
折騰了整整一個星期,這套聊天表情輸入功能總算做完了,包含表情翻頁動效與下拉刷新聊天記錄。由於沒有寫後端,這裡只呈現單方的表情選擇與發送流程,沒有雙方對話的效果。主要程式碼
用 ViewPager 實作跑馬燈輪播:支援多種切換動畫
最近接的專案需要一個跑馬燈式的圖片展示。上網翻了一圈,總覺得差那麼一點意思,索然自己動手寫一個。核心原理其實很單純:直接複用 ViewPager 這個控制項。它天生支援左