當系統元件無法滿足設計需求時,自訂 View 是解決之道。本文從零開始,涵蓋繼承選擇、XML 屬性定義、onMeasure/onDraw 繪製流程、觸控事件處理與效能優化,助你快速上手。
| 基類 | 適用場景 |
|---|---|
| View | 純繪製、簡單互動 (如圓形進度條、自訂圖表) |
| ViewGroup | 容器型元件,需管理子 View 佈局 (如流式佈局、標籤雲) |
| 現有 Widget (TextView, ImageView...) | 擴充既有功能 (如帶圖標的 Button、可展開 TextView) |
<resources>
<declare-styleable name="CustomCircleView">
<attr name="circleColor" format="color" />
<attr name="circleRadius" format="dimension" />
<attr name="showBorder" format="boolean" />
</declare-styleable>
</resources>
class CustomCircleView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val circleColor: Int
private val circleRadius: Float
private val showBorder: Boolean
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
init {
context.theme.obtainStyledAttributes(attrs, R.styleable.CustomCircleView, defStyleAttr, 0).apply {
circleColor = getColor(R.styleable.CustomCircleView_circleColor, Color.RED)
circleRadius = getDimension(R.styleable.CustomCircleView_circleRadius, 50f)
showBorder = getBoolean(R.styleable.CustomCircleView_showBorder, false)
recycle()
}
paint.color = circleColor
paint.style = if (showBorder) Paint.Style.STROKE else Paint.Style.FILL
paint.strokeWidth = 4f
}
// ...
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val desired = (circleRadius * 2 + paddingLeft + paddingRight).toInt()
val width = resolveSizeAndState(desired, widthMeasureSpec, 0)
val height = resolveSizeAndState(desired, heightMeasureSpec, 0)
setMeasuredDimension(width, height)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val cx = width / 2f
val cy = height / 2f
canvas.drawCircle(cx, cy, circleRadius, paint)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> { /* 按下邏輯 */; return true }
MotionEvent.ACTION_MOVE -> { /* 拖曳邏輯 */ }
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { /* 抬起/取消 */ }
}
return super.onTouchEvent(event)
}
Paint、Path、RectF 在 init 建立,勿在 onDraw 新建。onDraw 內不 new 物件、不做字串拼接、不做複雜運算。Bitmap 或 Picture 快取。setLayerType(LAYER_TYPE_SOFTWARE, null)。// 實現 Parcelable 或使用 SavedStateRegistry (Jetpack)
override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
return Bundle().apply {
putParcelable("super", superState)
putInt("color", circleColor)
}
}
override fun onRestoreInstanceState(state: Parcelable?) {
if (state is Bundle) {
circleColor = state.getInt("color")
super.onRestoreInstanceState(state.getParcelable("super"))
} else {
super.onRestoreInstanceState(state)
}
}
VISIBLE)、尺寸 > 0、未被父 View 裁剪、未設定 setWillNotDraw(true)。ACTION_DOWN 回傳 true 並呼叫 parent.requestDisallowInterceptTouchEvent(true)。遵循「測量→佈局→繪製」契約,善用工具類與快取策略,即可打造高效能、易維護的自訂 View。