Android验证码 简单实现Android验证码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android验证码 简单实现Android验证码

lizebin_bin   2021-03-25 我要评论
想了解简单实现Android验证码的相关内容吗,lizebin_bin在本文为您仔细讲解Android验证码的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,验证码,下面大家一起来学习吧。

安卓验证码的简单实现

我们经常在登录或者注册的时候要求输入验证码,这里简单介绍一下一种方法
效果如下

首先是要获取 随机的四个字母组合,我这里是将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);
        }
      }
    });

感觉还有挺多不足的地方,以后继续改进吧!

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们