在上一篇的文章中介绍了自定义控件的属性,详情见《详解Android自定义控件属性TypedArray以及attrs》。那么在这基础上实现随机验证码生成,里面的代码是自定义控件以及涉及到自定义view绘画。
1、先看实现的效果图
看到这个效果图是不是感觉还可以。那么就看看源码吧。
2、attr文件
<?xml version="1.0" enCoding="utf-8"?> <resources> <attr name="TitleText" format="string" /> <attr name="TitleTextcolor" format="color" /> <attr name="TitleTextSize" format="dimension" /> <declare-styleable name="AuthCodeVIEw"> <attr name="TitleText" /> <attr name="TitleTextcolor" /> <attr name="TitleTextSize" /> </declare-styleable> </resources>
3、布局layout
<linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" xmlns:authcodevIEw="http://schemas.androID.com/apk/res/com.example.authcodevIEw" androID:ID="@+ID/linearLayout1" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical" > <linearLayout androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" > <com.example.authcodevIEw.vIEw.AuthCodeVIEw androID:ID="@+ID/AuthCodeVIEw" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:padding="10dp" authcodevIEw:TitleText="3712" authcodevIEw:TitleTextcolor="#00ffff" authcodevIEw:TitleTextSize="40sp" /> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="点击验证码,换一张" /> </linearLayout> <linearLayout androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" > <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="输入验证码" /> <EditText androID:ID="@+ID/editText1" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:ems="10" androID:inputType="number" > <requestFocus /> </EditText> </linearLayout> <button androID:ID="@+ID/button1" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:text="验证" /> </linearLayout>
4、自定义AuthCodeVIEw.class
继承VIEw,重写了
onMeasure(int wIDthMeasureSpec,int heightmeasureSpec)
onDraw(Canvas canvas)方法。
看代码,有详细注释了。
package com.example.authcodevIEw.vIEw; import java.util.Random; import com.example.authcodevIEw.R; import androID.content.Context; import androID.content.res.TypedArray; import androID.graphics.Canvas; import androID.graphics.color; import androID.graphics.Paint; import androID.graphics.Rect; import androID.util.AttributeSet; import androID.util.TypedValue; import androID.vIEw.VIEw; public class AuthCodeVIEw extends VIEw { // 点数设置 public static final int POINT_NUM = 100; // 线段数设置 public static final int liNE_NUM = 2; //文本 private String mTitleText; // 文本的颜色 private int mTitleTextcolor; // 文本的大小 private int mTitleTextSize; String[] mCheckNum = new String[4]; Random random = new Random(); //绘制时控制文本绘制的范围 private Rect mBound; private Paint mPaint; public AuthCodeVIEw(Context context,AttributeSet attrs) { this(context,attrs,0); } public AuthCodeVIEw(Context context) { this(context,null); } /** * 获得我自定义的样式属性 * * @param context * @param attrs * @param defStyle */ public AuthCodeVIEw(Context context,AttributeSet attrs,int defStyle) { super(context,defStyle); /** * 获得我们所定义的自定义样式属性 */ TypedArray a = context.gettheme().obtainStyledAttributes(attrs,R.styleable.AuthCodeVIEw,defStyle,0); //获取在attr文件下,名字为AuthCodeVIEw的declare-styleable属性有几个 int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { //这个属性可以不要,因为都是随机产生 case R.styleable.AuthCodeVIEw_TitleText: mTitleText = a.getString(attr); break; case R.styleable.AuthCodeVIEw_TitleTextcolor: // 默认颜色设置为黑色 mTitleTextcolor = a.getcolor(attr,color.BLACK); break; case R.styleable.AuthCodeVIEw_TitleTextSize: // 默认设置为16sp,TypeValue也可以把sp转化为px mTitleTextSize = a.getDimensionPixelSize(attr,(int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP,16,getResources().getdisplayMetrics())); break; } } a.recycle(); mTitleText = randomText(); /** * 获得绘制文本的宽和高 */ mPaint = new Paint(); mPaint.setTextSize(mTitleTextSize); mBound = new Rect(); mPaint.getTextBounds(mTitleText,mTitleText.length(),mBound); this.setonClickListener(new OnClickListener() { @OverrIDe public voID onClick(VIEw v) { mTitleText = randomText(); postInvalIDate(); } }); } //随机产生验证码 private String randomText() { StringBuffer sbReturn = new StringBuffer(); for (int i = 0; i < 4; i++) { StringBuffer sb = new StringBuffer(); int randomInt = random.nextInt(10); mCheckNum[i] = sb.append(randomInt).toString(); sbReturn.append(randomInt); } return sbReturn.toString(); } //获取验证码 public String getAuthCode() { return mTitleText; } //重写这个方法,设置自定义view控件的大小 @OverrIDe protected voID onMeasure(int wIDthMeasureSpec,int heightmeasureSpec) { // super.onMeasure(wIDthMeasureSpec,heightmeasureSpec); int wIDth = 0; int height = 0; /** * 设置宽度 */ int specMode = MeasureSpec.getMode(wIDthMeasureSpec); int specsize = MeasureSpec.getSize(wIDthMeasureSpec); switch (specMode) { case MeasureSpec.EXACTLY:// 明确指定了 wIDth = getpaddingleft() + getpaddingRight() + specsize; break; case MeasureSpec.AT_MOST:// 一般为WARP_CONTENT wIDth = getpaddingleft() + getpaddingRight() + mBound.wIDth(); break; } /** * 设置高度 */ specMode = MeasureSpec.getMode(heightmeasureSpec); specsize = MeasureSpec.getSize(heightmeasureSpec); switch (specMode) { case MeasureSpec.EXACTLY:// 明确指定了 height = getpaddingtop() + getpaddingBottom() + specsize; break; case MeasureSpec.AT_MOST:// 一般为WARP_CONTENT height = getpaddingtop() + getpaddingBottom() + mBound.height(); break; } setMeasuredDimension(wIDth,height); } @OverrIDe protected voID onDraw(Canvas canvas) { //画背景颜色 mPaint.setcolor(color.BLUE); canvas.drawRect(0,getMeasureDWIDth(),getMeasuredHeight(),mPaint); //划线 mPaint.setcolor(mTitleTextcolor); int [] line; for(int i = 0; i < liNE_NUM; i ++) { //设置线宽 mPaint.setstrokeWIDth(5); line = getline(getMeasuredHeight(),getMeasureDWIDth()); canvas.drawline(line[0],line[1],line[2],line[3],mPaint); } // 绘制小圆点 int [] point; int randomInt; for(int i = 0; i < POINT_NUM; i ++) { //随机获取点的大小 randomInt = random.nextInt(5); point = getPoint(getMeasuredHeight(),getMeasureDWIDth()); canvas.drawCircle(point[0],point[1],randomInt,mPaint); } //绘制验证控件上的文本 int dx = 20; for(int i = 0; i < 4; i ++){ canvas.drawText("" + mCheckNum[i],dx,getHeight() / 2 + getPositon(mBound.height() / 2),mPaint); dx += (getWIDth() / 2 - mBound.wIDth() / 2) + i / 5 + 20; } // canvas.drawText(mTitleText,getWIDth() / 2 - mBound.wIDth() / 2,getHeight() / 2 + mBound.height() / 2,mPaint); } //计算验证码的绘制y点位置 private int getPositon(int height) { int tempPositoin = (int) (Math.random() * height); if (tempPositoin < 20) { tempPositoin += 20; } return tempPositoin; } // 随机产生点的圆心点坐标 public static int[] getPoint(int height,int wIDth) { int[] tempCheckNum = { 0,0 }; tempCheckNum[0] = (int) (Math.random() * wIDth); tempCheckNum[1] = (int) (Math.random() * height); return tempCheckNum; } //随机产生划线的起始点坐标和结束点坐标 public static int[] getline(int height,0 }; for (int i = 0; i < 4; i += 2) { tempCheckNum[i] = (int) (Math.random() * wIDth); tempCheckNum[i + 1] = (int) (Math.random() * height); } return tempCheckNum; } } 5、在MainActivity中怎么使用这个自定义AuthCodeVIEwpackage com.example.authcodevIEw; import com.example.authcodevIEw.vIEw.AuthCodeVIEw; import androID.os.Bundle; import androID.app.Activity; import androID.vIEw.VIEw; import androID.vIEw.VIEw.OnClickListener; import androID.Widget.EditText; import androID.Widget.Toast; public class MainActivity extends Activity implements OnClickListener { private AuthCodeVIEw mauthCodeVIEw; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); initUI(); } private voID initUI() { mauthCodeVIEw = (AuthCodeVIEw)findVIEwByID(R.ID.AuthCodeVIEw); findVIEwByID(R.ID.button1).setonClickListener(this); } @OverrIDe public voID onClick(VIEw v) { switch (v.getID()) { case R.ID.button1: EditText editText = (EditText)findVIEwByID(R.ID.editText1); String codeString = editText.getText().toString().trim(); if (codeString.equals(mauthCodeVIEw.getAuthCode())) { Toast.makeText(this,"验证码验证正确!",Toast.LENGTH_LONG).show(); }else { Toast.makeText(this,"验证码错误!",Toast.LENGTH_LONG).show(); } break; default: break; } } }
源码下载:Android生成随机验证码Demo
以上就是本文的全部内容,希望对大家的学习有所帮助。
总结以上是内存溢出为你收集整理的Android自定义控件深入学习 Android生成随机验证码全部内容,希望文章能够帮你解决Android自定义控件深入学习 Android生成随机验证码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)