Simple implementation of Android verification code
We often request to enter the verification code when logging in or registering, here a brief introduction one method
The effect is as follows
The first is to get a random four-letter combination, I am here to store 26 letters in an array, and then randomly generate 4 subscript values, take the four subscript corresponding letters as the verification code.
public class Randomchars {
char[] chars;
Public Randomchars () {
chars = new char[26];
for (int i = 0; i < i++) {
chars[i] = (char) (i +);
}
Public char[] Get4chars () {
char[] rlt = new Char[4];
for (int i = 0; i < rlt.length i++) {
int randomindex = (int) (Math.random () *);
Rlt[i] = Chars[randomindex];
}
Return RLT
}
}
Customize a CodeView for verification code, mainly in the OnDraw method of operation, not fine, not good in onmeasure control size position.
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)//rotate letter, random angle
canvas.drawtext (str, I * unitwidth + 5, getheight ()/2-mrect.centery (), Textpaint );
/**
* Very critical, rotating
/
canvas.save ()//Save state
Canvas.restore ();//Recovery
}
/**
* Reset Random color
* *
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));
Set the control and pass in four characters OK, verify that the input is correct, consider the case, so all the letters entered into uppercase, is generally case-insensitive.
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, "input correct", Toast.length_short). Show ();
else{
Toast.maketext (mainactivity.this, "Validation code input Error", Toast.length_short). Show ();
char[] GetChar = Randomchars.get4chars ();
str = new String (getchar);
Codeview.setchars (GetChar);
}
}
);
Feel there are quite a few deficiencies, and continue to improve it!
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.