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

Android 自定義 View 入門(一):從自訂屬性到 onMeasure 與 onDraw

編輯:關於 Android 程式設計

本講主題:自定義 View,且要求能夠在佈局檔案中重複使用。

整體步驟

1. 定義自定義屬性;
2. 在構造方法中讀取這些屬性;
3. 重寫 onMeasure(可選,但實務上通常需要,否則只能沿用系統預設);
4. 重寫 onDraw 完成繪製。

三個容易踩的細節

關於構造方法:我們重寫了三個構造方法,而佈局檔案 inflate 時調用的是只有兩個參數的那個。所以務必讓所有構造方法都最終委派到三參數版本,並在三參數版本中集中讀取自訂屬性。

關於測量:不重寫 onMeasure 時,系統給的高度與寬度一律是 MATCH_PARENT;即使你在 XML 中寫成 WRAP_CONTENT,最終也會表現成 MATCH_PARENT。

MeasureSpec 的三種 specMode:

EXACTLY:明確指定了具體數值,或者 MATCH_PARENT;
AT_MOST:子佈局被限制在一個最大值內,對應 WRAP_CONTENT;
UNSPECIFIED:子佈局想多大就多大,實務中很少用到。

效果預覽

佈局檔案 activity_main.xml

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:custom="https://schemas.android.com/apk/res/com.example.customview1"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.view.CustomTitleView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        custom:titleText="1314"
        custom:titleTextColor="#ff0000"
        custom:titleTextSize="50sp" />

</RelativeLayout>

務必引入命名空間 xmlns:custom="https://schemas.android.com/apk/res/項目包名",後面才能使用 custom: 前綴。

屬性聲明 res/values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomTitleView">
        <attr name="titleText" format="string" />
        <attr name="titleTextColor" format="color" />
        <attr name="titleTextSize" format="dimension" />
    </declare-styleable>
</resources>

format 用於聲明該屬性的取值型別,可選值包括:string、color、dimension、integer、enum、reference、float、boolean、fraction、flag。

自定義 View 本體

public class CustomTitleView extends View {

    private String mTitleText;   // 文本內容
    private int mTitleTextColor; // 文本顏色
    private int mTitleTextSize;  // 文本大小
    private Rect mBound;         // 文本繪製邊界
    private Paint mPaint;

    public CustomTitleView(Context context) {
        this(context, null);
    }

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

    /** 集中處理自訂屬性 */
    public CustomTitleView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs, R.styleable.CustomTitleView, defStyle, 0);
        int n = a.getIndexCount();

        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.CustomTitleView_titleText:
                    mTitleText = a.getString(attr);
                    break;
                case R.styleable.CustomTitleView_titleTextColor:
                    mTitleTextColor = a.getColor(attr, Color.BLACK);
                    break;
                case R.styleable.CustomTitleView_titleTextSize:
                    mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue
                            .applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,
                                    getResources().getDisplayMetrics()));
                    break;
            }
        }
        a.recycle();   // 用完務必回收

        // 先量一次文本尺寸
        mPaint = new Paint();
        mPaint.setTextSize(mTitleTextSize);
        mBound = new Rect();
        mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);

        // 加個互動:點擊換一組隨機數,順便體驗 postInvalidate
        this.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                mTitleText = randomText();
                postInvalidate();
            }
        });
    }

    /** 生成 4 位不重複隨機數 */
    private String randomText() {
        Random random = new Random();
        Set<Integer> set = new HashSet<Integer>();
        while (set.size() < 4) {
            set.add(random.nextInt(10));
        }
        StringBuffer sb = new StringBuffer();
        for (Integer i : set) {
            sb.append("" + i);
        }
        return sb.toString();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = 0;
        int height = 0;

        // 寬度
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);
        switch (specMode) {
            case MeasureSpec.EXACTLY:   // 明確指定
                width = getPaddingLeft() + getPaddingRight() + specSize;
                break;
            case MeasureSpec.AT_MOST:   // WRAP_CONTENT
                width = getPaddingLeft() + getPaddingRight() + mBound.width();
                break;
        }

        // 高度
        specMode = MeasureSpec.getMode(heightMeasureSpec);
        specSize = MeasureSpec.getSize(heightMeasureSpec);
        switch (specMode) {
            case MeasureSpec.EXACTLY:
                height = getPaddingTop() + getPaddingBottom() + specSize;
                break;
            case MeasureSpec.AT_MOST:
                height = getPaddingTop() + getPaddingBottom() + mBound.height();
                break;
        }

        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 背景
        mPaint.setColor(Color.YELLOW);
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);

        // 居中繪製文字
        mPaint.setColor(mTitleTextColor);
        canvas.drawText(mTitleText,
                getWidth() / 2 - mBound.width() / 2,
                getHeight() / 2 + mBound.height() / 2,
                mPaint);
    }
}

主界面

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

幾點複盤

與直接使用 TextView 相比,這個自定義 View 表面上看不出優勢,所以我在裡面加了一個點擊事件,每次生成一組四位隨機數。沿著這個思路再往 onDraw 裡加些噪點,就能改造成一個驗證碼控件——這才是自定義 View 真正的用武之地:標準控件做不到的呈現方式。

另外注意 onDraw 中文字垂直居中的算法:baseline 需要在中心點再加上文字高度的一半,直接用 getHeight() / 2 會導致視覺偏上。

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