Implementación simple del código de verificación de Android

Implementación simple del código de verificación de Android

A menudo, al iniciar sesión o registrarse, es necesario ingresar un código de verificación, aquí brevemente una forma de
realizar lo siguiente

Escriba la descripción de la imagen aquí


La primera es obtener una combinación aleatoria de cuatro letras. Aquí, almaceno 26 letras en una matriz y luego genero aleatoriamente 4 valores de subíndice, y tomo las letras correspondientes a estos cuatro valores de subíndice como código de verificación.

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;
    }
}

Personalice un CodeView para dibujar el código de verificación. Se opera principalmente en el método onDraw. No soy bueno para aprender y no puedo controlar el tamaño y la posición en 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));
    }

Establezca el control y pase cuatro caracteres y está bien. Al verificar si la entrada es correcta, considere el problema de las mayúsculas, por lo que convierta todas las letras de entrada a mayúsculas, generalmente no distingue entre mayúsculas y minúsculas.

        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);
                }
            }
        });

Siento que todavía hay muchas deficiencias, ¡seguir mejorando en el futuro!

Supongo que te gusta

Origin blog.csdn.net/lizebin_bin/article/details/51035050
Recomendado
Clasificación