Android验证码实现的步骤如下:在布局文件中添加一个输入框,用于输入验证码;
Android验证码实现的步骤如下:
1. 在布局文件中添加一个EditText输入框,用于输入验证码;
2. 创建一个类继承View,并重写onDraw()方法,在该方法中实现随机生成验证码;
3. 在Activity中实例化上述类,并将其添加到布局文件中;
4. 创建一个器,EditText输入框的文本变化,并与绘制出来的验证码进行比对;
5. 根据比对结果,进行相应的处理。
以下是具体的代码实现:
//1. 布局文件
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> android:id="@+id/et_code" android:layout_width="match_parent" android:layout_height="wrap_content" /> android:id="@+id/cv_code" android:layout_width="wrap_content" android:layout_height="wrap_content" />
//2. 继承View的类
public class CodeView extends View {
private Paint paint;
private String code;
public CodeView(Context context) {
super(context);
init();
}
public CodeView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CodeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
paint = new Paint();
code = getRandomString();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//绘制验证码
drawCode(canvas);
}
private void drawCode(Canvas canvas){
//设置画笔属性
paint.setColor(Color.BLACK);
paint.setTextSize(30);
paint.setAntiAlias(true);
//绘制验证码
for(int i=0;i canvas.drawText(code.charAt(i)+"",10+(i*30),30,paint); } } //获取随机字符串 private String getRandomString(){ String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; StringBuilder sb=new StringBuilder(); Random random=new Random(); for(int i=0;i<4;i++){ int number= 本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(17条)