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

動手做一個 Android 驗證碼控件:自定義 View 全流程實踐

編輯:關於 Android 程式設計

本文在鴻洋大神《Android 自定義 View(一)》的基礎上做了擴展,同時也整理了不少關於自定義 View 構造函數的細節,適合剛入門自定義控件的同學當作一份完整練手案例。

第一步:聲明自定義屬性

自定義控件要能從 XML 裡配置,得先用 declare-styleable 標籤把屬性集合定義出來。這裡我們準備了文字顏色、文字大小、背景顏色和文字個數四個屬性:

 <declare-styleable name="CustomTitleView">
 <attr name="titleColor" format="color" />
 <attr name="titleSize" format="dimension" />
 <attr name="titleBackground" format="color" />
 <attr name="titleLenth" format="integer" />
 </declare-styleable> 

format 決定了這個屬性能接受什麼型別的值,常見的有下面這些:

reference:資源 ID,效果等同於 @string、@drawable 這類資源引用。
color:顏色值,支援 6 位或 8 位十六進位,用法和 TextView 的 textColor 一致。
boolean:true 或 false。
dimension:尺寸值,如 px、dip、dp、sp。
float:浮點數。
integer:整數。
string:字串,如 TextView 的 text。
fraction:百分比數值。
enum:把屬性限定為幾個固定值,例如 LinearLayout 的 orientation 只能填 vertical 或 horizontal。
flag:用於位或運算的多選組合。

第二步:自定義 View 的標準四步

一個自定義 View 的套路基本是固定的:

1. 定義自定義屬性;
2. 在構造方法中把屬性取出來;
3. 重寫 onMeasure 處理測量;
4. 重寫 onDraw 完成繪製。

其中 onMeasure 並非一定要重寫,如果只是繼承系統現成組件,往往可以省下來。先把需要的成員變數列出來:

 //文本
private StringBuffer mTitleText;
//文本的顏色
private int mTitleColor;
//文本的大小
private int mTitleSize;
//背景顏色
private int mBackground;
//控制生成的隨機字符串長度
private int mLenth;
//繪制時控制文本繪制的范圍
private Rect mBound;
//畫筆
private Paint mPaint;
//隨機數對象
private Random random = new Random();
//字符串邊距
private int padding_left;
//隨機的值
String[] data = {"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", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; 

第三步:三個構造函數的由來

自定義 View 通常要寫三個構造函數,它們的調用時機常被誤解,這裡說清楚:

1. 代碼中直接 new 出實例時,走第一個構造函數。
2. 在 XML 布局中引用時,走第二個構造函數。
3. 在 XML 中引用且標籤上帶了自定義屬性時,走的仍然是第二個構造函數。

換句話說,系統默認只會調用前兩個,第三個一般由我們自己在構造函數中間接調用(例如在第二個裡 this(context, attrs, 0))。而屬性的讀取,就是在第三個構造函數中透過 obtainStyledAttributes 完成的。

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

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

 public CustomTitleView(Context context, AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  setOnClickListener(this);
  TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomTitleView);
  int n = typedArray.getIndexCount();
  for (int i = 0; i < n; i++) {
   int attr = typedArray.getIndex(i);
   switch (attr) {
   case R.styleable.CustomTitleView_titleColor:
    mTitleColor = typedArray.getColor(attr, Color.BLACK); break;
   case R.styleable.CustomTitleView_titleSize:
    mTitleSize = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
      TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); break;
   case R.styleable.CustomTitleView_titleBackground:
    mBackground = typedArray.getColor(attr, Color.BLACK); break;
   case R.styleable.CustomTitleView_titleLenth:
    mLenth = typedArray.getInteger(attr, 4); break;
   }
  }
  typedArray.recycle();
  mPaint = new Paint();
  randomText();
  mPaint.setTextSize(mTitleSize);
  mBound = new Rect();
  mPaint.getTextBounds(mTitleText.toString(), 0, mTitleText.length(), mBound);
 } 

注意 obtainStyledAttributes 的第二個參數,傳的就是 attrs.xml 裡 declare-styleable 的 name。

第四步:重寫 onMeasure

驗證碼的寬高取決於文字,所以 wrap_content 時必須自己算。核心邏輯是:先判斷 MeasureSpec 的模式,精確值直接取,AT_MOST 則用文字尺寸加上 padding 推算:

 /**
  * 計算寬高
  * @param lenth widthMeasureSpec 或 heightMeasureSpec
  * @param isWidth true 計算寬度,false 計算高度
  */
 private int getMeasuredLength(int lenth, boolean isWidth) {
  if (isWidth) {
   if (MeasureSpec.getMode(lenth) == MeasureSpec.EXACTLY) {
    // 設置了精確尺寸,直接返回
    return MeasureSpec.getSize(lenth);
   } else {
    // wrap_content 時需要自己計算
    if (MeasureSpec.getMode(lenth) == MeasureSpec.AT_MOST) {
     mPaint.setTextSize(mTitleSize);
     mPaint.getTextBounds(mTitleText.toString(), 0, mTitleText.length(), mBound);
     float textwidth = mBound.width();
     int desired = (int) (getPaddingLeft() + textwidth + getPaddingRight());
     return Math.min(desired, MeasureSpec.getSize(lenth));
    }
   }
  } else {
   if (MeasureSpec.getMode(lenth) == MeasureSpec.EXACTLY) {
    return MeasureSpec.getSize(lenth);
   } else {
    if (MeasureSpec.getMode(lenth) == MeasureSpec.AT_MOST) {
     mPaint.setTextSize(mTitleSize);
     mPaint.getTextBounds(mTitleText.toString(), 0, mTitleText.length(), mBound);
     float texthgeight = mBound.height();
     int desired = (int) (getPaddingTop() + texthgeight + getPaddingBottom());
     return Math.min(desired, MeasureSpec.getSize(lenth));
    }
   }
  }
  return 0;
 } 

一般情況下,計算所需寬度的口訣是:左右 padding 之和,再加上內容(文字或圖片)的寬度。如果同時有圖片和文字,就取兩者中較大的那個。

 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  setMeasuredDimension(getMeasuredLength(widthMeasureSpec, true),
    getMeasuredLength(heightMeasureSpec, false));
 } 

順帶把 MeasureSpec 的三種 specMode 記牢:

EXACTLY:明確數值或 match_parent。
AT_MOST:子 View 被限制在一個最大值內,通常對應 wrap_content。
UNSPECIFIED:父容器不給限制,想多大就多大,日常很少遇到,多見於 ScrollView 之類的容器。

getMode() 負責判斷模式,getSize() 負責取出尺寸,兩者搭配使用:

 // xx 表示 widthMeasureSpec 或 heightMeasureSpec
if (MeasureSpec.getMode(xx) == MeasureSpec.EXACTLY) {
 // match_parent 或指定了具體數值,如 android:layout_width="100dp"
 // 直接 getSize 拿結果
} else if (MeasureSpec.getMode(xx) == MeasureSpec.AT_MOST) {
 // wrap_content,需要自己計算
} else {
 // 未指定尺寸,通常出現在父容器為 AdapterView 的場景
} 

第五步:onDraw 畫出歪歪扭扭的字符

驗證碼的關鍵在於「不好認」:每個字符隨機粗細、隨機傾斜、帶下劃線。做法是在繪製每個字符前,先隨機改一次 Paint 的樣式。

 @Override protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  padding_left = 0;
  mPaint.setColor(mBackground);
  canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);
  mPaint.setColor(mTitleColor);
  for (int i = 0; i < mTitleText.length(); i++) {
   randomTextStyle(mPaint);
   padding_left += mPaint.measureText(String.valueOf(mTitleText.charAt(i))) + 10;
   canvas.drawText(String.valueOf(mTitleText.charAt(i)), padding_left,
     getHeight() / 2 + mBound.height() / 2, mPaint);
  }
 }

 private void randomTextStyle(Paint paint) {
  paint.setFakeBoldText(random.nextBoolean());      // true 為粗體
  float skewX = random.nextInt(11) / 10;
  skewX = random.nextBoolean() ? skewX : -skewX;
  paint.setTextSkewX(skewX);                        // 負數右斜,正數左斜
  paint.setUnderlineText(true);                     // 下劃線
  paint.setStrikeThruText(false);                   // 刪除線
 } 

drawText 的四個參數依次是:要畫的文字、x 座標(相當於左邊距)、y 座標(基線位置)、以及 Paint 實例。想讓文字垂直居中,可以用控件高度的一半再加上文字高度的一半來推算基線。

第六步:布局中引用

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
  xmlns:cq="https://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="horizontal">
  <chapter.com.rxjavachapter.CustomTitleView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:padding="10dp"
   cq:titleBackground="@android:color/black"
   cq:titleColor="#ff0000"
   cq:titleLenth="4"
   cq:titleSize="10sp" />
 </RelativeLayout> 

根布局上的 xmlns:cq="https://schemas.android.com/apk/res-auto" 是命名空間聲明,cq 這個前綴可以換成任意字母,後續就用它點出 attrs 裡定義的屬性名。

第七步:點擊換一組驗證碼

驗證碼當然要能刷新。構造函數裡已經註冊了 OnClickListener,所以只要實現接口,重新生成字串並重繪即可:

 @Override public void onClick(View v) {
  randomText();
  postInvalidate();
 }

 /** 獲得隨機的字符串 */
 private void randomText() {
  mTitleText = new StringBuffer();
  for (int i = 0; i < mLenth; i++) {
   mTitleText.append(data[(int) (Math.random() * data.length)]);
  }
 }

 /** 獲取當前驗證碼 */
 public String getCode() { return mTitleText.toString(); }

 /** 判斷輸入是否正確,忽略大小寫 */
 public boolean isEqual(String code) {
  if (code != null) {
   return code.toUpperCase().equals(getCode().toUpperCase()) ? true : false;
  } else {
   return false;
  }
 } 

最後對外開放 getCode() 和 isEqual() 兩個方法,業務層就能取驗證碼或做校驗了。這個例子比較基礎,實際項目裡還可以加上干擾線、噪點、字符隨機旋轉等增強手法。

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