android 客户端生成随机验证码的实现

来源:互联网 发布:网络特产商城行业分析 编辑:程序博客网 时间:2024/06/05 05:33
由于项目中要用到验证码,自己找了些资料,试着就把这个验证码给做了出来,代码不是很多,比较的简单,下面给大家看看我是怎么实现该功能的:

 

源码地址下载:http://download.csdn.net/detail/u014608640/7268905

 

首先当然是写XML咯,贴上代码

[html] view plain copy 在CODE上查看代码片派生到我的代码片
  1. <LinearLayout   
  2.       android:layout_width="match_parent"  
  3.       android:layout_height="wrap_content"  
  4.       android:orientation="horizontal"  
  5.       android:id="@+id/yh"  
  6.       >  
  7.         
  8.       <TextView   
  9.           android:text="用户名:"  
  10.           android:layout_width="wrap_content"  
  11.           android:layout_height="wrap_content"  
  12.           />  
  13.         
  14.       <EditText   
  15.           android:layout_width="fill_parent"  
  16.           android:layout_height="wrap_content"  
  17.           />  
  18.         
  19.   </LinearLayout>  
  20.     
  21.     
  22.     
  23.   <LinearLayout   
  24.       android:layout_width="match_parent"  
  25.       android:layout_height="wrap_content"  
  26.       android:orientation="horizontal"  
  27.       android:layout_below="@id/yh"  
  28.       android:id="@+id/pwd"  
  29.       >  
  30.         
  31.       <TextView   
  32.           android:text="密码:"  
  33.           android:layout_width="wrap_content"  
  34.           android:layout_height="wrap_content"  
  35.           />  
  36.         
  37.       <EditText   
  38.           android:layout_width="fill_parent"  
  39.           android:layout_height="wrap_content"  
  40.           />  
  41.         
  42.   </LinearLayout>  
  43.   
  44.     
  45.   <LinearLayout  
  46.                android:layout_width="match_parent"  
  47.                android:layout_height="wrap_content"  
  48.                android:gravity="center_vertical"  
  49.                android:layout_marginTop="4dp"  
  50.                android:orientation="horizontal"  
  51.                android:layout_below="@id/pwd"  
  52.                android:id="@+id/code"  
  53.                 >  
  54.   
  55.                <LinearLayout  
  56.                    android:layout_width="wrap_content"  
  57.                    android:layout_height="wrap_content"  
  58.                    android:layout_marginBottom="10dp"  
  59.                    android:layout_marginLeft="10dp"  
  60.                    android:layout_marginRight="10dp"  
  61.                    android:layout_marginTop="5dp"  
  62.                    android:orientation="horizontal" >  
  63.   
  64.                    <TextView  
  65.                        android:layout_width="wrap_content"  
  66.                        android:layout_height="wrap_content"  
  67.                        android:layout_marginLeft="20dp"  
  68.                        android:layout_marginRight="5dp"  
  69.                        android:text="验 证 码:"  
  70.                        android:textColor="#000000" />  
  71.   
  72.                    <EditText  
  73.                        android:id="@+id/vc_code"  
  74.                        android:layout_width="60dp"  
  75.                        android:layout_height="wrap_content"  
  76.                        android:layout_weight="1"  
  77.                        android:background="#0000"  
  78.                        android:maxLength="4"  
  79.                        android:paddingBottom="10dp"  
  80.                        android:paddingLeft="10dp"  
  81.                        android:paddingTop="10dp"  
  82.                        android:textColor="#000000"  
  83.                        android:textSize="14sp" />  
  84.                </LinearLayout>  
  85.   
  86.                <ImageView  
  87.                    android:id="@+id/vc_image"  
  88.                    android:layout_width="wrap_content"  
  89.                    android:layout_height="match_parent"  
  90.                    android:layout_marginBottom="10dp"  
  91.                    android:layout_marginTop="5dp"  
  92.                    android:layout_weight="1" />  
  93.   
  94.                <Button  
  95.                    android:id="@+id/vc_shuaixi"  
  96.                    android:layout_width="40dp"  
  97.                    android:layout_height="wrap_content"  
  98.                    android:background="@android:color/transparent"  
  99.                    android:layout_gravity="center_vertical"  
  100.                    android:text="刷新验证码"  
  101.                    android:textStyle="italic"  
  102.                    android:layout_marginTop="5dp"  
  103.                    android:layout_marginBottom="10dp"  
  104.                    android:layout_marginLeft="5dp"  
  105.                    android:layout_marginRight="5dp"  
  106.                    android:textColor="#7f7f7f"  
  107.                    android:textSize="12sp" />  
  108.            </LinearLayout>  
  109.     
  110.   <LinearLayout   
  111.       android:layout_width="match_parent"  
  112.       android:layout_height="wrap_content"  
  113.       android:layout_below="@id/code"  
  114.       android:orientation="horizontal"  
  115.       >  
  116.       <Button   
  117.           android:id="@+id/vc_ok"  
  118.           android:layout_width="match_parent"  
  119.           android:layout_height="wrap_content"  
  120.           android:text="确定"  
  121.           />  
  122.         
  123.   </LinearLayout>  


下面贴一下MainActivity的代码:

里面的注释很详细,就不多说了!

[html] view plain copy 在CODE上查看代码片派生到我的代码片
  1. import android.os.Bundle;  
  2. import android.app.Activity;  
  3. import android.util.Log;  
  4. import android.view.Menu;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.Button;  
  8. import android.widget.EditText;  
  9. import android.widget.ImageView;  
  10. import android.widget.Toast;  
  11.   
  12. public class MainActivity extends Activity {  
  13.       
  14.     ImageView vc_image; //图标  
  15.     Button vc_shuaixi,vc_ok; //确定和刷新验证码  
  16.     String getCode=null; //获取验证码的值  
  17.     EditText vc_code; //文本框的值  
  18.       
  19.     @Override  
  20.     protected void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.activity_main);  
  23.           
  24.         vc_image=(ImageView)findViewById(R.id.vc_image);  
  25.         vc_image.setImageBitmap(Code.getInstance().getBitmap());  
  26.         vc_code=(EditText) findViewById(R.id.vc_code);  
  27.           
  28.         getCode=Code.getInstance().getCode(); //获取显示的验证码  
  29.         Log.e("info", getCode+"----");  
  30.         vc_shuaixi=(Button)findViewById(R.id.vc_shuaixi);  
  31.         vc_shuaixi.setOnClickListener(new OnClickListener() {  
  32.               
  33.             @Override  
  34.             public void onClick(View v) {  
  35.                 // TODO Auto-generated method stub  
  36.                 vc_image.setImageBitmap(Code.getInstance().getBitmap());  
  37.                 getCode=Code.getInstance().getCode();  
  38.             }  
  39.         });  
  40.           
  41.         vc_ok=(Button)findViewById(R.id.vc_ok);  
  42.         vc_ok.setOnClickListener(new OnClickListener() {  
  43.               
  44.             @Override  
  45.             public void onClick(View v) {  
  46.                 // TODO Auto-generated method stub  
  47.             String  v_code=vc_code.getText().toString().trim();  
  48.             if(v_code==null||v_code.equals("")){  
  49.                 Toast.makeText(MainActivity.this, "没有填写验证码", 2).show();  
  50.             }else if(!v_code.equals(getCode)){  
  51.                 Toast.makeText(MainActivity.this, "验证码填写不正确", 2).show();  
  52.             }else{  
  53.                 Toast.makeText(MainActivity.this, "操作成功", 2).show();  
  54.             }  
  55.               
  56.             }  
  57.         });  
  58.           
  59.     }  


最后贴一下做验证码必须的一个类Code:

[html] view plain copy 在CODE上查看代码片派生到我的代码片
  1. import java.util.Random;  
  2.   
  3. import android.graphics.Bitmap;  
  4. import android.graphics.Canvas;  
  5. import android.graphics.Color;  
  6. import android.graphics.Paint;  
  7. import android.graphics.Bitmap.Config;  
  8.   
  9.   
  10. public class Code {  
  11.   
  12.     private static final char[] CHARS = {  
  13.         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
  14.         'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',   
  15.         'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',  
  16.         'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',   
  17.         'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'  
  18.     };  
  19.       
  20.     private static Code bpUtil;  
  21.     private Code(){};  
  22.     public static Code getInstance() {  
  23.         if(bpUtil == null)  
  24.             bpUtil = new Code();  
  25.         return bpUtil;  
  26.     }  
  27.     //default settings  
  28.     private static final int DEFAULT_CODE_LENGTH = 4;//验证码的长度  这里是4位  
  29.     private static final int DEFAULT_FONT_SIZE = 60;//字体大小  
  30.     private static final int DEFAULT_LINE_NUMBER = 3;//多少条干扰线  
  31.     private static final int BASE_PADDING_LEFT = 20; //左边距  
  32.     private static final int RANGE_PADDING_LEFT = 35;//左边距范围值    
  33.     private static final int BASE_PADDING_TOP = 42;//上边距  
  34.     private static final int RANGE_PADDING_TOP = 15;//上边距范围值  
  35.     private static final int DEFAULT_WIDTH = 200;//默认宽度.图片的总宽  
  36.     private static final int DEFAULT_HEIGHT = 70;//默认高度.图片的总高  
  37.     private  final int DEFAULT_COLOR=0xdf;//默认背景颜色值  
  38.       
  39.     //settings decided by the layout xml  
  40.     //canvas width and height  
  41.     private int width = DEFAULT_WIDTH;  
  42.     private int height = DEFAULT_HEIGHT;   
  43.       
  44.     //random word space and pading_top  
  45.     private int base_padding_left = BASE_PADDING_LEFT;  
  46.     private int range_padding_left = RANGE_PADDING_LEFT;  
  47.     private int base_padding_top = BASE_PADDING_TOP;  
  48.     private int range_padding_top = RANGE_PADDING_TOP;  
  49.       
  50.     //number of chars, lines; font size  
  51.     private int codeLength = DEFAULT_CODE_LENGTH;  
  52.     private int line_number = DEFAULT_LINE_NUMBER;  
  53.     private int font_size = DEFAULT_FONT_SIZE;  
  54.       
  55.     //variables  
  56.     private String code;//保存生成的验证码  
  57.     private int padding_left, padding_top;  
  58.     private Random random = new Random();  
  59.       
  60.     private Bitmap createBitmap() {  
  61.         padding_left = 0;  
  62.           
  63.         Bitmap bp = Bitmap.createBitmap(width, height, Config.ARGB_8888);   
  64.         Canvas c = new Canvas(bp);  
  65.   
  66.         code = createCode();  
  67.           
  68.         c.drawColor(Color.rgb(DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_COLOR));  
  69.         Paint paint = new Paint();  
  70.         paint.setTextSize(font_size);  
  71.           
  72.         for (int i = 0; i < code.length(); i++) {  
  73.             randomTextStyle(paint);  
  74.             randomPadding();  
  75.             c.drawText(code.charAt(i) + "", padding_left, padding_top, paint);  
  76.         }  
  77.   
  78.         for (int i = 0; i < line_number; i++) {  
  79.             drawLine(c, paint);  
  80.         }  
  81.           
  82.         c.save( Canvas.ALL_SAVE_FLAG );//保存    
  83.         c.restore();//  
  84.         return bp;  
  85.     }  
  86.       
  87.     public String getCode() {  
  88.         return code.toLowerCase();  
  89.     }  
  90.       
  91.     public Bitmap getBitmap(){  
  92.         return createBitmap();  
  93.     }  
  94.     private String createCode() {  
  95.         StringBuilder buffer = new StringBuilder();  
  96.         for (int i = 0; i < codeLength; i++) {  
  97.             buffer.append(CHARS[random.nextInt(CHARS.length)]);  
  98.         }  
  99.         return buffer.toString();  
  100.     }  
  101.       
  102.     private void drawLine(Canvas canvas, Paint paint) {  
  103.         int color = randomColor();  
  104.         int startX = random.nextInt(width);  
  105.         int startY = random.nextInt(height);  
  106.         int stopX = random.nextInt(width);  
  107.         int stopY = random.nextInt(height);  
  108.         paint.setStrokeWidth(1);  
  109.         paint.setColor(color);  
  110.         canvas.drawLine(startX, startY, stopX, stopY, paint);  
  111.     }  
  112.       
  113.     private int randomColor() {  
  114.         return randomColor(1);  
  115.     }  
  116.   
  117.     private int randomColor(int rate) {  
  118.         int red = random.nextInt(256) / rate;  
  119.         int green = random.nextInt(256) / rate;  
  120.         int blue = random.nextInt(256) / rate;  
  121.         return Color.rgb(red, green, blue);  
  122.     }  
  123.       
  124.     private void randomTextStyle(Paint paint) {  
  125.         int color = randomColor();  
  126.         paint.setColor(color);  
  127.         paint.setFakeBoldText(random.nextBoolean());  //true为粗体,false为非粗体  
  128.         float skewX = random.nextInt(11) / 10;  
  129.         skewX = random.nextBoolean() ? skewX : -skewX;  
  130.         paint.setTextSkewX(skewX); //float类型参数,负数表示右斜,整数左斜  
  131. //      paint.setUnderlineText(true); //true为下划线,false为非下划线  
  132. //      paint.setStrikeThruText(true); //true为删除线,false为非删除线  
  133.     }  
  134.       
  135.     private void randomPadding() {  
  136.         padding_left += base_padding_left + random.nextInt(range_padding_left);  
  137.         padding_top = base_padding_top + random.nextInt(range_padding_top);  
  138.     }  
  139. }  


代码已经贴完毕,可以试着做一下!

0 0
原创粉丝点击