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

Android 自定義 View 實作隨機圖形驗證碼的完整流程

編輯:關於 Android 程式設計

驗證碼這種小功能,幾乎每個登入或註冊類的頁面都會用到。這篇文章以「隨機生成圖形驗證碼」為切入點,但真正的重點其實在於自定義 View 的開發套路——從屬性聲明、構造函數的選擇,到 onMeasure 與 onDraw 的職責分工,這些才是值得反覆咀嚼的部分。

自定義 View 的四個基本步驟

無論要畫什麼,自定義 View 的骨架大致是固定的:

1. 定義自定義屬性;
2. 在構造方法中把這些屬性取出來;
3. 重寫 onMeasure;
4. 重寫 onDraw。

其中 onMeasure 並非一定要重寫,但實務上大多數情況都繞不開它,後面會說明原因。

先搞懂四個構造函數

自定義 View 有四種構造函數,分別對應不同的使用場景:

1、CustomView(Context context)
直接用 Java 代碼 new 出實例時走這條路。

2、CustomView(Context context, AttributeSet attrs)
在 XML 佈局檔中宣告時呼叫的就是它。attrs 這個參數的作用,是把 XML 裡寫的自定義屬性一併帶進 View 內部。

3、CustomView(Context context, AttributeSet attrs, int defStyleAttr)
第三個參數是預設 Style,指的是目前 Application 或 Activity 所套用 Theme 中的預設樣式,只有在明確指定時才會生效。

4、CustomView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
這個版本是 API 21 才補上的。

動手寫代碼

第一步:宣告屬性

在 res/values/ 底下新增一個 attr.xml,把要用到的屬性和取值類型都定義好。

 <?xml version="1.0" encoding="utf-8"?> <resources> <attr name="text" format="string" /> <attr name="textColor" format="color" /> <attr name="textSize" format="dimension" /> <attr name="bgColor" format="color" /> <declare-styleable name="CustomView"> <attr name="text" /> <attr name="textColor" /> <attr name="textSize" /> <attr name="bgColor" /> </declare-styleable> </resources> 

這裡定義了文字內容、文字顏色、文字大小與背景顏色四個屬性。format 用來標明屬性值的類型,可選值共有十種:string、color、dimension、integer、enum、reference、float、boolean、fraction 以及 flag。

第二步:在佈局中引用

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:custom="https://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <com.per.customview01.view.CustomView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:padding="10dp" custom:bgColor="#FF27FF28" custom:text="J2RdWQG" custom:textColor="#ff0000" custom:textSize="36dp" /> </RelativeLayout> 

關鍵是別忘了加上 xmlns:custom="https://schemas.android.com/apk/res-auto" 這行命名空間宣告。在 Android Studio 中可以直接使用 res-auto 命名空間,如此一來就不必再寫自定義 View 的完整類別路徑。

第三步:在構造方法中讀取屬性

 /** * 文本 */ private String mText; /** * 文本的顏色 */ private int mTextColor; /** * 文本的大小 */ private int mTextSize; /** * 文本的背景顏色 */ private int mBgCplor; private Rect mBound; private Paint mPaint; public CustomView(Context context) { this(context, null); } public CustomView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CustomView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); /** * 獲得我們所定義的自定義樣式屬性 */ TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomView, defStyleAttr, 0); for (int i = 0; i < a.getIndexCount(); i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.CustomView_text: mText = a.getString(attr); break; case R.styleable.CustomView_textColor: // 默認文本顏色設置為黑色 mTextColor = a.getColor(R.styleable.CustomView_textColor, Color.BLACK); break; case R.styleable.CustomView_bgColor: // 默認文本背景顏色設置為藍色 mBgCplor = a.getColor(R.styleable.CustomView_bgColor, Color.BLUE); break; case R.styleable.CustomView_textSize: // 默認設置為16sp,TypeValue也可以把sp轉化為px mTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); break; } } a.recycle(); // 獲得繪制文本的寬和高 mPaint = new Paint(); mPaint.setTextSize(mTextSize); mBound = new Rect(); mPaint.getTextBounds(mText, 0, mText.length(), mBound); } 

這裡重寫了三個構造方法。前面提過,XML 佈局呼叫的是兩參數版本,因此務必讓所有構造方法最終都彙集到三參數版本,並在其中統一處理屬性讀取。

一開始,一參數與二參數版本通常是這樣寫的:

 public CustomView(Context context) { super(context); } public CustomView(Context context, AttributeSet attrs) { super(context, attrs); } 

要注意的是,這裡的 super 應該改成 this,讓參數少的構造方法逐層引用參數多的版本:

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

第四步:重寫 onMeasure 與 onDraw

 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPaint.setColor(mBgCplor); canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint); mPaint.setColor(mTextColor); canvas.drawText(mText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint); } 

整個繪製流程是從 ViewRoot 的 performTraversals 方法開始,歷經 measure、layout、draw 三個階段,最後才把 View 呈現在螢幕上:

• 測量 onMeasure():決定 View 的寬高,也就是它有多大;
• 布局 onLayout():決定 View 在父容器 ViewGroup 中的位置;
• 繪製 onDraw():真正把內容畫到螢幕上。

仔細的人會發現,佈局檔裡我們把寬高設成了 wrap_content,但上面這張圖的結果顯然不對。原因在於系統幫我們測出來的值預設是 MATCH_PARENT:如果我們明確給了寬高數值,系統就照著給;但只要不是明確數值,不論寫 WRAP_CONTENT 還是 MATCH_PARENT,系統回報的結果都是 MATCH_PARENT。所以當我們用了 wrap_content,就必須自己動手測量,也就是重寫 onMeasure。

 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heighMode = MeasureSpec.getMode(heightMeasureSpec); int heighSize = MeasureSpec.getSize(heightMeasureSpec); setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : getPaddingLeft() + getPaddingRight() + mBound.width(), heighMode == MeasureSpec.EXACTLY ? heighSize : getPaddingTop() + getPaddingBottom() + mBound.height()); }

MeasureSpec 封裝的是父佈局傳給子佈局的測量要求,specMode 主要有三種:EXACTLY 代表確切值(明確數值或 MATCH_PARENT),此時由父元素決定子元素大小,子元素必須被限制在指定範圍內,忽略自身尺寸;AT_MOST 代表至多這麼大,對應的通常是 wrap_content;而未指定的情況則由子元素自行決定。

這下尺寸就對了。回到主題,把驗證碼的邏輯補進來,完整代碼如下。

 package com.per.customview01.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.View; import com.per.customview01.R; import java.util.Random; /** * @author: adan * @description: * @projectName: CustomView01 * @date: 2016-06-12 * @time: 10:26 */ public class CustomView extends View { private static final char[] CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; /** * 初始化生成隨機數的類 */ private Random mRandom = new Random(); /** * 初始化可變字符串 */ private StringBuffer sb = new StringBuffer(); /** * 文本 */ private String mText; /** * 文本的顏色 */ private int mTextColor; /** * 文本的大小 */ private int mTextSize; /** * 文本的背景顏色 */ private int mBgCplor; private Rect mBound; private Paint mPaint; public CustomView(Context context) { this(context, null); } public CustomView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CustomView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); /** * 獲得我們所定義的自定義樣式屬性 */ TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomView, defStyleAttr, 0); for (int i = 0; i < a.getIndexCount(); i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.CustomView_text: mText = a.getString(attr); break; case R.styleable.CustomView_textColor: // 默認文本顏色設置為黑色 mTextColor = a.getColor(R.styleable.CustomView_textColor, Color.BLACK); break; case R.styleable.CustomView_bgColor: // 默認文本背景顏色設置為藍色 mBgCplor = a.getColor(R.styleable.CustomView_bgColor, Color.BLUE); break; case R.styleable.CustomView_textSize: // 默認設置為16sp,TypeValue也可以把sp轉化為px mTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); break; } } a.recycle(); // 獲得繪制文本的寬和高 mPaint = new Paint(); mPaint.setTextSize(mTextSize); mBound = new Rect(); mPaint.getTextBounds(mText, 0, mText.length(), mBound); this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mText = createCode(); mTextColor = randomColor(); mBgCplor = randomColor(); //View重新調用一次draw過程,以起到界面刷新的作用 postInvalidate(); } }); } /** * 生成驗證碼 */ public String createCode() { sb.delete(0, sb.length()); // 使用之前首先清空內容 for (int i = 0; i < 6; i++) { sb.append(CHARS[mRandom.nextInt(CHARS.length)]); } Log.e("生成驗證碼", sb.toString()); return sb.toString(); } /** * 隨機顏色 */ private int randomColor() { sb.delete(0, sb.length()); // 使用之前首先清空內容 String haxString; for (int i = 0; i < 3; i++) { haxString = Integer.toHexString(mRandom.nextInt(0xFF)); if (haxString.length() == 1) { haxString = "0" + haxString; } sb.append(haxString); } Log.e("隨機顏色", "#" + sb.toString()); return Color.parseColor("#" + sb.toString()); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heighMode = MeasureSpec.getMode(heightMeasureSpec); int heighSize = MeasureSpec.getSize(heightMeasureSpec); setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : getPaddingLeft() + getPaddingRight() + mBound.width(), heighMode == MeasureSpec.EXACTLY ? heighSize : getPaddingTop() + getPaddingBottom() + mBound.height()); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPaint.setColor(mBgCplor); canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint); mPaint.setColor(mTextColor); canvas.drawText(mText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint); } } 

最後掛上一個點擊事件:每按一次,就重新產生驗證碼、字色與底色,再把結果印到 Log 裡方便觀察。

以上就是本次分享的全部內容,希望對正在練習自定義 View 的朋友有幫助。

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