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

Android 自定義 View 詳解:以 CrossView 為例

編輯:關於 Android 程式設計

當系統提供的現成控件無法滿足需求時,自定義 View 就成了必備技能。本文以一個繪製「十字圖形」的 CrossView 為例,完整走過自定義視圖、自定義屬性以及在 XML 中使用的三個環節。

一、自定義 View 類

核心要點包括:在構造函數中透過 AttributeSet 取得系統傳入的屬性;重寫 onMeasure() 決定視圖的測量尺寸;重寫 onDraw() 完成實際繪製。

public class CrossView extends View {
    private float mRotation;
    private Paint mPaint;

    public CrossView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(0xFFFFFFFF);

        // 使用 obtainStyledAttributes 讀取存放於 AttributeSet 中的自定義屬性
        TypedArray arr = getContext().obtainStyledAttributes(attrs, R.styleable.cross);
        int color = arr.getColor(R.styleable.cross_android_color, Color.WHITE);
        float rotation = arr.getFloat(R.styleable.cross_rotation, 0f);
        arr.recycle(); // 用完記得回收,內部有緩存
        setColor(color);
        setRotation(rotation);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(calculateMeasure(widthMeasureSpec),
                calculateMeasure(heightMeasureSpec));
    }

    float[] mPoints = {0.5f, 0f, 0.5f, 1f, 0f, 0.5f, 1f, 0.5f};

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save(); // 繪圖操作應受 save() 與 restore() 約束
        int scale = getWidth();
        canvas.scale(scale, scale);
        canvas.rotate(mRotation);
        canvas.drawLines(mPoints, mPaint); // 繪製十字的兩條線
        canvas.restore();
    }

    private static final int DEFAULT_SIZE = 100;

    private int calculateMeasure(int measureSpec) {
        int result = (int) (DEFAULT_SIZE * getResources().getDisplayMetrics().density);
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {
            result = Math.min(result, specSize);
        }
        return result;
    }
}

其中 onDraw 裡的 canvas.save() 與 canvas.restore() 是一對好搭檔,確保縮放、旋轉等變換不會相互影響;而 calculateMeasure 則依據 MeasureSpec 的模式(EXACTLY 或 AT_MOST)決定最終尺寸。

二、自定義屬性

在 res/values/ 目錄下的 XML 檔案中,用 <declare-styleable> 宣告自定義屬性:

<resources>
    <declare-styleable name="cross">
        <attr name="android:color"/>
        <attr name="rotation" format="string"/>
    </declare-styleable>
</resources>

三、在 XML 中使用自定義 View

使用前必須先為視圖宣告命名空間,然後即可像使用普通控件一樣引用 CrossView,並傳入自定義屬性:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:example="https://schemas.android.com/apk/res/com.example"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.example.CrossView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <com.example.CrossView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        example.rotation="30"
        android:color="#0000FF" />
</LinearLayout>

透過這個例子可以看到,自定義 View 一旦搭配上自定義屬性,就能像系統原生控件一樣在佈局檔中靈活配置,極大提升了封裝性與可複用性。

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