安卓驗證碼的簡單實現
我們經常在登入或者註冊的時候要求輸入驗證碼,這裡簡單介紹一下一種方法
效果如下
首先是要擷取 隨機的四個字母組合,我這裡是將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); } } });
感覺還有挺多不足的地方,以後繼續改進吧!
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。