Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

打造一個規範的自定義 View:從反面範例說起

編輯:關於 Android 程式設計

先看一個「能跑但不規範」的版本

需求很簡單:畫一個圓。以下是最直覺的寫法:

public class CircleView extends View {
    private int mColor = Color.RED;
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public CircleView(Context context) {
        super(context);
        init();
    }

    public CircleView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint.setColor(mColor);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int width = getWidth();
        int height = getHeight();
        int radius = Math.min(width, height) / 2;
        canvas.drawCircle(width / 2, height / 2, radius, mPaint);
    }
}

對應的 XML:

<com.ryg.chapter_4.ui.CircleView
    android:background="#000000"
    android:id="@+id/circleView1"
    android:layout_height="100dp"
    android:layout_margin="20dp"
    android:layout_width="match_parent" />

圓是畫得出來,但這個 View 有兩個不容忽視的缺陷:

android:padding 屬性完全無效。在 XML 設了 padding,畫出來卻毫無變化。
使用 wrap_content 等同於 match_parent。把 layout_width 改成 wrap_content,圓不會縮小,反而照樣填滿父容器。

這兩點讓它在真實專案中幾乎無法使用——任何需要留白的版面配置都會失效。

規範的版本:覆寫 onMeasure 與 onDraw

要解決上述問題,必須自己處理測量與 padding。

public class CircleView extends View {
    private int mColor = Color.RED;
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public CircleView(Context context) {
        super(context);
        init();
    }

    public CircleView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
        mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);
        a.recycle();
        init();
    }

    private void init() {
        mPaint.setColor(mColor);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(200, 200);
        } else if (widthSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(200, heightSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSpecSize, 200);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        final int paddingLeft = getPaddingLeft();
        final int paddingRight = getPaddingRight();
        final int paddingTop = getPaddingTop();
        final int paddingBottom = getPaddingBottom();
        int width = getWidth() - paddingLeft - paddingRight;
        int height = getHeight() - paddingTop - paddingBottom;
        int radius = Math.min(width, height) / 2;
        canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2, radius, mPaint);
    }
}

兩個關鍵改動:onMeasure 中針對 AT_MOST(也就是 wrap_content 對應的模式)給出預設尺寸 200;onDraw 中把四邊 padding 從可用區域中扣除,圓心座標也相應加上 paddingLeft / paddingTop 的偏移。

加上自定義屬性

先在 values 下建立 attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CircleView">
        <attr name="circle_color" format="color" />
    </declare-styleable>
</resources>

這裡定義了一個名為 CircleView 的屬性集合,裡面只有一個 color 格式的屬性 circle_color。

在建構子中解析(前面完整程式碼已包含):

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);
a.recycle();

XML 中使用時,記得先宣告 namespace:

<com.ryg.chapter_4.ui.CircleView
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:background="#000000"
    android:id="@+id/circleView1"
    android:layout_height="100dp"
    android:layout_margin="20dp"
    android:layout_width="wrap_content"
    android:padding="20dp"
    app:circle_color="@color/light_green" />

namespace 宣告也可以放在根布局上,效果相同。使用方式與系統屬性無異:app:circle_color="@color/light_green"。別忘了 a.recycle(),TypedArray 是需要回收的資源。

自定義 View 必備常識

margin 屬性可以直接使用,因為它由父容器控制,不需要自己在 onMeasure 中處理。
直接繼承 View 或 ViewGroup 的類別,必須自己處理 wrap_content,否則它就等同 match_parent。
View 要在 onDraw 中處理 padding;ViewGroup 則要在 onMeasure 與 onLayout 中處理 padding 和 margin。
View 中的 post 方法可以取代 handler,它會把 Runnable 排入 View 所屬行程的訊息佇列,語意更貼近 UI 操作。
在 onDetachedFromWindow 中停止動畫,避免 View 被移除後動畫仍在跑造成記憶體洩漏。
存在滑動巢狀關係時,務必處理滑動衝突,例如用 requestDisallowInterceptTouchEvent 協調父子層級的攔截行為。

想寫出漂亮又健壯的自定義 View 並不容易,唯有大量閱讀原始碼、多寫、多測,才能逐步建立手感。自己動手造一個輪子,再拿成熟元件來對比,差距與不足自然浮現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved