安卓驗證碼的簡單實現
我們經常在登錄或者注冊的時候要求輸入驗證碼,這里簡單介紹一下一種方法
效果如下

首先是要獲取 隨機的四個字母組合,我這里是將26個字母存儲到一個數組中,然后隨機生成4個下標值,取這四個下標值對應的字母作為驗證碼。
public class RandomChars { char[] chars; public RandomChars() { chars = new char[26]; for (int i = 0; i < 26; i++) { chars[i] = (char) (i + 65); } } public char[] get4Chars() { char[] rlt = new char[4]; for (int i = 0; i < rlt.length; i++) { int randomIndex = (int) (Math.random() * 26); rlt[i] = chars[randomIndex]; } return rlt; }}自定義一個CodeView進行驗證碼的繪制,主要在onDraw方法中操作,學藝不精,還不能好好在onMeasure中控制大小位置等。
float unitWidth = (float) getWidth() / (float) chars.length; for (int i = 0; i < chars.length; i++) { String str = chars[i] + ""; textPaint.getTextBounds(str, 0, str.length(), mRect); resetColor(); int angel = (int) (Math.random()*(8-(-8)+1)+(-8)); canvas.rotate(angel);//旋轉字母,隨機角度 canvas.drawText(str, i * unitWidth + 5, getHeight() / 2 - mRect.centerY(), textPaint); /** * 很關鍵,旋轉 */ canvas.save();//保存狀態 canvas.restore();//恢復 }/** * 重新設置隨機顏色 */ private void resetColor() { int r = (int) (Math.random() * 230 - 30); int g = (int) (Math.random() * 230 - 30); int b = (int) (Math.random() * 230 - 30); textPaint.setColor(Color.rgb(r, g, b)); }設置該控件并傳入四個字符就ok了,驗證是否輸入正確的時候,考慮到大小寫問題,所以將輸入的字母全部轉換成大寫,一般都是不區分大小寫。
submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String inputStr = input.getText().toString(); inputStr = inputStr.toUpperCase(); str = str.toUpperCase(); if (str.equals(inputStr)) { Toast.makeText(MainActivity.this, "輸入正確", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MainActivity.this, "驗證碼輸入錯誤", Toast.LENGTH_SHORT).show(); char[] getchar = randomChars.get4Chars(); str = new String(getchar); codeView.setChars(getchar); } } });感覺還有挺多不足的地方,以后繼續改進吧!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
|
新聞熱點
疑難解答