萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 自訂 View 完整入門指南(繪製、屬性、觸控、生命週期)

前言

當系統元件無法滿足設計需求時,自訂 View 是解決之道。本文從零開始,涵蓋繼承選擇、XML 屬性定義、onMeasure/onDraw 繪製流程、觸控事件處理與效能優化,助你快速上手。

1. 選擇繼承基類

基類適用場景
View純繪製、簡單互動 (如圓形進度條、自訂圖表)
ViewGroup容器型元件,需管理子 View 佈局 (如流式佈局、標籤雲)
現有 Widget (TextView, ImageView...)擴充既有功能 (如帶圖標的 Button、可展開 TextView)

2. 定義 XML 自訂屬性 (res/values/attrs.xml)

<resources>
    <declare-styleable name="CustomCircleView">
        <attr name="circleColor" format="color" />
        <attr name="circleRadius" format="dimension" />
        <attr name="showBorder" format="boolean" />
    </declare-styleable>
</resources>

3. 取得屬性並初始化 (Kotlin)

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
    }
    // ...
}

4. 測量與繪製核心

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)
}

5. 觸控事件處理

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)
}

6. 效能優化關鍵

  • 物件複用:Paint、Path、RectF 在 init 建立,勿在 onDraw 新建。
  • 避免分配:onDraw 內不 new 物件、不做字串拼接、不做複雜運算。
  • 裁剪與快取:複雜圖形可預先繪製至 Bitmap 或 Picture 快取。
  • 硬體加速:複雜 Path/文字可能關閉硬體加速 setLayerType(LAYER_TYPE_SOFTWARE, null)。

7. 狀態保存與還原

// 實現 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)
    }
}

常見坑點

Q: 自訂屬性在 XML 無提示?
A: 重建專案 (Build → Rebuild Project) 刷新 R 檔與資源索引。
Q: onDraw 不觸發?
A: 確認 View 可見 (VISIBLE)、尺寸 > 0、未被父 View 裁剪、未設定 setWillNotDraw(true)。
Q: 觸控事件被父 View 攔截?
A: 在 ACTION_DOWN 回傳 true 並呼叫 parent.requestDisallowInterceptTouchEvent(true)。

遵循「測量→佈局→繪製」契約,善用工具類與快取策略,即可打造高效能、易維護的自訂 View。

copyright © 萬盛學電腦網 all rights reserved