Android實現隨機驗證碼——自訂View

來源:互聯網
上載者:User

標籤:

一、問題描述

  熟悉web開發中童鞋們都知道為了防止惡意破解、惡意提交、刷票等我們在提交表單資料時,都會使用隨機驗證碼功能。在Android應用中我們同樣需要這一功能,該如何?呢,下面我們就自訂一個隨機驗證碼View控制項實現這一需求,並且具備通用性,需要的時候在介面中直接加入這個View組件即可。

二、案例介紹

  案例運行效果

 

  案例所涉及組件

1、CheckView 自訂的驗證碼控制項,主要重寫onDraw方法實現圖形繪製

2、Config:用於對驗證碼控制項參數的配置,像畫點點數、劃線數、背景顏色的設定

3、CheckUtil:驗證碼相關工具類,實現例如隨機的點座標、隨機線段起始和結束點座標、驗證碼校正等功能

4、MainActivity:測試應用

三、功能實現
1、編寫Config組件
/** * 功能:用於對驗證碼控制項參數的配置* */public class Config {    // 驗證碼更新時間    public  static  final  int  PTEDE_TIME = 1200;    // 點數設定    public  static  final  int  POINT_NUM = 100;    // 線段數設定    public  static  final  int LINE_NUM = 2;    //設定背景顏色    public  static  final  int COLOR=Color.BLUE;    //隨機資料長度    public static  int TEXT_LENGTH=4;    //設定驗證碼字型大小    public static int TEXT_SIZE=30;}
2、CheckUtil 組件
/** * 功能:驗證碼相關工具類 * */public class CheckUtil{    /**     * 產生隨機數字     * @return     */    public static int [] getCheckNum(){        int [] tempCheckNum = new int[Config.TEXT_LENGTH];        for(int i = 0; i < Config.TEXT_LENGTH; i++){            tempCheckNum[i] = (int) (Math.random() * 10);        }        return tempCheckNum;    }    /**     * 隨機產生劃線的起始點座標和結束點座標     * @param height 傳入CheckView的高度值     * @param width 傳入CheckView的寬度值     * @return 起始點座標和結束點座標     */    public static int[] getLine(int height, int width){        int [] tempCheckNum = {0,0,0,0};        for(int i = 0; i < 4; i+=2){            tempCheckNum[i] = (int) (Math.random() * width);            tempCheckNum[i + 1] = (int) (Math.random() * height);            }        return tempCheckNum;    }    /**     * 隨機產生點的圓心點座標     * @param height 傳入CheckView的高度值     * @param width 傳入CheckView的寬度值     * @return     */    public static int[] getPoint(int height, int width){        int [] tempCheckNum = {0,0,0,0};        tempCheckNum[0] = (int) (Math.random() * width);        tempCheckNum[1] = (int) (Math.random() * height);        return tempCheckNum;    }        /**     *  驗證是否正確     * @param userCheck 使用者輸入的驗證碼     * @param checkNum  驗證控制項產生的隨機數     * @return     */    public static boolean checkNum(String userCheck, int[] checkNum){        if(userCheck.length() != 4 ){                return false;        }        String checkString = "";        for (int i = 0; i < 4; i++) {            checkString += checkNum[i];        }        if(userCheck.equals(checkString)){            return true;        }        else {            return false;        }    }    /**     *  計算驗證碼的繪製y點位置     * @param height 傳入CheckView的高度值     * @return     */        public static int getPositon(int height){        int tempPositoin = (int) (Math.random() * height);        if(tempPositoin < 20){            tempPositoin += 20;        }        return tempPositoin;    }}
3、自訂驗證碼控制項CheckView
public class CheckView extends View{    Context mContext;    int [] CheckNum = null;    Paint mTempPaint = new Paint();    // 驗證碼        public CheckView(Context context, AttributeSet attrs) {        super(context, attrs);        mContext = context;        mTempPaint.setAntiAlias(true);        mTempPaint.setTextSize(Config.TEXT_SIZE);        mTempPaint.setStrokeWidth(3);    }        public void onDraw(Canvas canvas){        canvas.drawColor(Config.COLOR);        final int height = getHeight();//獲得CheckView控制項的高度        final int width = getWidth();//獲得CheckView控制項的寬度        int dx = 40;        for(int i = 0; i < 4; i ++){//繪製驗證控制項上的文本            canvas.drawText("" + CheckNum[i],  dx, CheckUtil.getPositon(height), mTempPaint);            dx += width/ 5;        }        int [] line;        for(int i = 0; i < Config.LINE_NUM; i ++){//劃線            line = CheckUtil.getLine(height, width);            canvas.drawLine(line[0], line[1], line[2], line[3], mTempPaint);        }        // 繪製小圓點        int [] point;        for(int i = 0; i < Config.POINT_NUM; i ++)    {//畫點            point=CheckUtil.getPoint(height, width);            canvas.drawCircle(point[0], point[1], 1, mTempPaint);        }    }        public void setCheckNum(int [] chenckNum) {//設定驗證碼        CheckNum = chenckNum;    }        public int[] getCheckNum() {//獲得驗證碼        return CheckNum;    }        public void invaliChenkNum() {        invalidate();    }    }
4、編寫MainActivity測試代碼
public class MainActivity extends Activity implements View.OnClickListener{    private CheckAction mCheckView ;    private TextView mShowPassViwe;    private  EditText mEditPass;    private  Button mSubmit;    private Button mRef;    // 驗證碼:    private int [] checkNum =null;    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);         initView();        initCheckNum();    }        public void initView(){        mCheckView = (CheckView) findViewById(R.id.checkView);        mShowPassViwe = (TextView) findViewById(R.id.checkpass);        mEditPass = (EditText) findViewById(R.id.checkTest);        mSubmit = (Button) findViewById(R.id.submit);        mRef = (Button) findViewById(R.id.ref);                mSubmit.setOnClickListener(this);        mRef.setOnClickListener(this);    }        // 初始化驗證碼並且重新整理介面    public void initCheckNum(){        checkNum = CheckUtil.getCheckNum();        mCheckView.setCheckNum(checkNum);        mCheckView.invaliChenkNum();    }    public void onClick(View v) {        switch (v.getId()){                case R.id.submit:            String userInput = mEditPass.getText().toString();            if(CheckUtil.checkNum(userInput, checkNum)){                setPassString("通過");                Toast.makeText(this, "通過", 1200).show();            }else{                setPassString("未通過");                Toast.makeText(this, "未通過", 1200).show();                }            break;        case R.id.ref:            initCheckNum();            break;        default:            break;        }    }    public void setPassString(String passString) {        mShowPassViwe.setText(passString);    }}

Android實現隨機驗證碼——自訂View

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.