編輯:關於 Android 程式設計
一般來說,Android 實作自訂控制項無非三種途徑:
Ⅰ、繼承現有控制項,擴充它的功能。
Ⅱ、把現有控制項組合起來,做出功能更強的複合控制項。
Ⅲ、直接重寫 View,打造一個全新的控制項。
本文要談的是三者中最難的一種。判斷時機很簡單:當原生控制項怎麼湊都不合用時,就該考慮自己寫一個。而重寫 View 大致離不開這四步:
Ⅰ、在 onMeasure() 中測量自身尺寸,讓它能自適應各種版面需求。
Ⅱ、在 onDraw() 中藉助 Canvas 與 Paint 這對搭檔繪製內容。
Ⅲ、在 onLayout() 中決定控制項的顯示位置。
Ⅳ、在 onTouchEvent() 中處理觸控事件。
思維導圖如下:

空談無益,直接看兩個小案例。
先看示意圖:

一眼就能看出這個圖形可以拆成三塊:外層的環、內部的圓、以及中間的文字。思路清楚之後,剩下的只是在 onDraw 裡逐個畫出來。這裡為了簡化,把控制項寬度直接設為螢幕寬度。
首先定義自訂屬性,方便呼叫方調整:
<declare-styleable name="circleView"> <attr name="textSize" format="dimension" /> <attr name="text" format="string" /> <attr name="circleColor" format="color" /> <attr name="arcColor" format="color" /> <attr name="textColor" format="color" /> <attr name="startAngle" format="integer" /> <attr name="sweepAngle" format="integer" /> </declare-styleable>
Ⅰ、textSize——中間文字的大小
Ⅱ、text——中間顯示的文字
Ⅲ、circleColor——內圓顏色
Ⅳ、arcColor——外環顏色
Ⅴ、textColor——文字顏色
Ⅵ、startAngle——外環起始角度
Ⅶ、sweepAngle——外環掃描角度
接著在初始化工法中把這些屬性讀出來:
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.circleView); if (ta != null) { circleColor = ta.getColor(R.styleable.circleView_circleColor, 0); arcColor = ta.getColor(R.styleable.circleView_arcColor, 0); textColor = ta.getColor(R.styleable.circleView_textColor, 0); textSize = ta.getDimension(R.styleable.circleView_textSize, 50); text = ta.getString(R.styleable.circleView_text); startAngle = ta.getInt(R.styleable.circleView_startAngle, 0); sweepAngle = ta.getInt(R.styleable.circleView_sweepAngle, 90); ta.recycle(); } 這裡要多提一句:用完 TypedArray 一定要呼叫 recycle() 釋放資源,養成習慣。
然後在初始化裡準備畫筆、算出中心座標與外接矩形:
private void init() { int length = Math.min(width, height); mCircleXY = length / 2; mRadius = length * 0.5f / 2; mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCirclePaint.setColor(circleColor); mRectF = new RectF(length * 0.1f, length * 0.1f, length * 0.9f, length * 0.9f); mArcPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mArcPaint.setColor(arcColor); mArcPaint.setStyle(Paint.Style.STROKE); mArcPaint.setStrokeWidth((width * 0.1f)); mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTextPaint.setTextSize(textSize); mTextPaint.setColor(textColor); mTextPaint.setTextAlign(Align.CENTER); } 把自訂屬性分配給各自的畫筆之後,就能在 onDraw 裡收尾:
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawSth(canvas); } private void drawSth(Canvas canvas) { canvas.drawCircle(mCircleXY, mCircleXY, mRadius, mCirclePaint); canvas.drawArc(mRectF, startAngle, sweepAngle, false, mArcPaint); canvas.drawText(text, 0, text.length(), mCircleXY, mCircleXY + textSize / 4, mTextPaint); } 要注意的是,畫環形必須指定一個矩形範圍,並給定起始角度與掃描角度,而這些值都來自自訂屬性。
運行結果:

條形圖在圖表系統裡再常見不過,靜態版本長這樣:

做法是把一個個矩形畫出來,每個矩形的 x 座標往右平移一個單位。仔細看會發現:各bar的起點不一,終點卻是同一條基線——起點座標用 Random 隨機產生剛剛好。
首先在 onMeasure 中算出每根矩形的寬與高。這裡每根 bar 的高度等同 View 高度,寬度則是螢幕寬度的 80% 除以數量。接著依寬高初始化畫筆;之所以需要具體尺寸,是因為我用了 LinearGradient(線性渲染)讓漸層更逼真。另外這個控制項是動態的,靠 onDraw 不斷重繪來更新,為了避免刷新過快,這裡每隔 300 毫秒才重畫一次:
public class VolumneView extends View { private Paint mPaint; private int mCount; private int mWidth; private int mRectHeight; private int mRectWidth; private LinearGradient mLinearGradient; private double mRandom; private float mcurrentHeight; public static final int OFFSET = 5; public VolumneView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context, attrs); } private void initView(Context context, AttributeSet attrs) { mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setColor(Color.GREEN); mPaint.setStyle(Paint.Style.FILL); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.volumneView); if (ta != null) { mCount = ta.getInt(R.styleable.volumneView_count, 6); ta.recycle(); } } public VolumneView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VolumneView(Context context) { this(context, null); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = getMeasuredWidth(); mRectHeight = getMeasuredHeight(); mRectWidth = (int) (mWidth * 0.8 / mCount); mLinearGradient = new LinearGradient(0, 0, mRectWidth, mRectHeight, Color.GREEN, Color.YELLOW, TileMode.CLAMP); mPaint.setShader(mLinearGradient); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (int i = 0; i < mCount; i++) { mRandom = Math.random(); mcurrentHeight = (float) (mRectHeight * mRandom); float width = (float) (mWidth * 0.4 / 2 + OFFSET); canvas.drawRect(width + i * mRectWidth, mcurrentHeight, width + (i + 1) * mRectWidth, mRectHeight, mPaint); } postInvalidateDelayed(300); } 運行結果:

後記:透過這兩個小控件,相信各位對自訂控制項的基本步驟已經有概念了。當然,真要做出好-quality 的控件,還得在 these 步驟上反覆打磨,加油!
Android 應用安裝流程解析
了解 Android 應用的安裝流程,有助於除錯、發版與理解系統行為。本文從打包、簽名到安裝路徑做一項整理。 從原始碼到 APK Android 專案會先將 Java
Android layout_weight 怎麼用:三種情境圖解與 Fragment 特例
layout_weight 是 LinearLayout 裡最實用也最容易被誤解的屬性。它的作用是:在扣除固定尺寸後,把剩餘空間依權重比例分配給子元素。搭配 layout
Android Studio 下的串口 JNI 開發實作
本文以在 Android Studio 中進行串口 JNI 開發為主題,記錄從環境建立、Gradle 設定到編譯產生 .so 的完整流程。1. 開發環境Mac OS X、
adb 連接不上手機?兩種方法解決設備識別問題
驅動明明裝好了,adb devices 卻怎麼也列不出設備,這困擾過不少人。問題通常不在驅動,而在 adb 不知道該用哪個 USB 廠商 ID 去匹配你的機器。 Wind