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

Android 自訂 View 實作隨機驗證碼

編輯:關於 Android 程式設計

自訂 View 是 Android 開發中常見的進階主題。這個範例會建立一個可點擊刷新的隨機驗證碼 View,示範自訂屬性、onMeasure、onDraw 與點擊事件的基本流程。

自訂 View 的基本步驟

  1. 定義自訂屬性。
  2. 在構造方法中取得屬性。
  3. 必要時重寫 onMeasure。
  4. 重寫 onDraw 繪製內容。

1. 定義自訂屬性

在 res/values/attrs.xml 中宣告屬性:

<resources>
    <attr name="titleText" format="string" />
    <attr name="titleTextColor" format="color" />
    <attr name="titleTextSize" format="dimension" />

    <declare-styleable name="CustomTitleView">
        <attr name="titleText" />
        <attr name="titleTextColor" />
        <attr name="titleTextSize" />
    </declare-styleable>
</resources>

2. 在布局中使用

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

    <com.example.customview01.view.CustomTitleView
        android:layout_width="200dp"
        android:layout_height="100dp"
        custom:titleText="3712"
        custom:titleTextColor="#ff0000"
        custom:titleTextSize="40sp" />
</RelativeLayout>

3. 取得自訂屬性

public CustomTitleView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

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

    int count = a.getIndexCount();

    for (int i = 0; i < count; 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();
}

4. 繪製文字

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

初始效果:

5. 處理 wrap_content

如果布局中將寬高設為 wrap_content,自訂 View 需要自行計算合適尺寸,否則系統可能會使用預設行為。

可以重寫 onMeasure:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    if (widthMode == MeasureSpec.EXACTLY) {
        width = widthSize;
    } else {
        mPaint.setTextSize(mTitleTextSize);
        mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);
        width = mBound.width() + getPaddingLeft() + getPaddingRight();
    }

    if (heightMode == MeasureSpec.EXACTLY) {
        height = heightSize;
    } else {
        mPaint.setTextSize(mTitleTextSize);
        mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);
        height = mBound.height() + getPaddingTop() + getPaddingBottom();
    }

    setMeasuredDimension(width, height);
}

調整後效果:

6. 加入點擊刷新

讓 View 在點擊時重新產生一組隨機數字,並呼叫 postInvalidate() 重新繪製。

this.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mTitleText = randomText();
        postInvalidate();
    }
});

private String randomText() {
    Random random = new Random();
    Set<Integer> set = new HashSet<>();

    while (set.size() < 4) {
        set.add(random.nextInt(10));
    }

    StringBuilder sb = new StringBuilder();
    for (Integer i : set) {
        sb.append(i);
    }

    return sb.toString();
}

點擊後效果:

透過這個範例,可以練習自訂 View 的完整流程。若要進一步做成驗證碼,還可以加入干擾線、隨機點、旋轉文字與顏色變化,讓畫面更豐富。

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