Implementation of random verification code generated by Android client

Source: Internet
Author: User

because the project to use the verification code, I found some information, try to put this verification code to do out, the code is not many, the comparison is simple, the following to see how I realize the function:

Source Address Download : http://download.csdn.net/detail/u014608640/7268905

First of all, of course, write the XML, put the code

 <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android:orie           ntation= "Horizontal" android:id= "@+id/yh" > <textview android:text= "username:" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content"/> <ed          Ittext android:layout_width= "fill_parent" android:layout_height= "Wrap_content"/> </LinearLayout> <linearlayout android:layout_width= "Match_parent" Android:layout_heigh       t= "wrap_content" android:orientation= "horizontal" android:layout_below= "@id/yh" android:id= "@+id/pwd" > <textview android:text= "Password:" android:layout_width= "Wrap_content" a ndroid:layout_height= "Wrap_content"/> <edittext android:layout_width= "fill_parent "Android:layout_height= "Wrap_content"/> </LinearLayout> <linearlayout android:layou T_width= "Match_parent" android:layout_height= "wrap_content" android:gravity= "center_vertical "Android:layout_margintop=" 4DP "android:orientation=" Horizontal "android:lay                    out_below= "@id/pwd" android:id= "@+id/code" > <linearlayout Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" and Roid:layout_marginbottom= "10DP" android:layout_marginleft= "10DP" Android:layout_marg                    inright= "10DP" android:layout_margintop= "5DP" android:orientation= "Horizontal" > <textview android:layout_width= "Wrap_content" Android: Layout_height= "Wrap_contEnt "android:layout_marginleft=" 20DP "android:layout_marginright=" 5DP " android:text= "Verification Code:" Android:textcolor= "#000000"/> <ed                        Ittext android:id= "@+id/vc_code" android:layout_width= "60DP" android:layout_height= "Wrap_content" android:layout_weight= "1" Andro                        Id:background= "#0000" android:maxlength= "4" android:paddingbottom= "10DP" android:paddingleft= "10DP" android:paddingtop= "10DP" and                Roid:textcolor= "#000000" android:textsize= "14sp"/> </LinearLayout>                     <imageview android:id= "@+id/vc_image" android:layout_width= "Wrap_content" Androidoid:layout_height= "Match_parent" android:layout_marginbottom= "10DP" android:layout_m argintop= "5DP" android:layout_weight= "1"/> <button android:id=                    "@+id/vc_shuaixi" android:layout_width= "40DP" android:layout_height= "Wrap_content" Android:background= "@android: Color/transparent" android:layout_gravity= "center_vertic Al "android:text=" Refresh Captcha "android:textstyle=" Italic "android:layou                     t_margintop= "5DP" android:layout_marginbottom= "10DP" android:layout_marginleft= "5DP" android:layout_marginright= "5DP" android:textcolor= "#7f7f7f" and Roid:textsize= "12SP"/> </LinearLayout> <linearlayout android:layout_width= "Match_paren T "Android:layout_height= "Wrap_content" android:layout_below= "@id/code" android:orientation= "Horizontal" > <Bu Tton android:id= "@+id/vc_ok" android:layout_width= "match_parent" android:layout_height= "Wra P_content "android:text=" OK "/> </LinearLayout>


Here's the code for Mainactivity:

The inside of the note is very detailed, not much to say!

Import Android.os.bundle;import android.app.activity;import Android.util.log;import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.imageview;import Android.widget.toast;public class MainActivity    Extends Activity {ImageView vc_image;//Icon Button VC_SHUAIXI,VC_OK;//Confirm and refresh Captcha String getcode=null;//Get Verification code value EditText Vc_code; The value of the text box @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); vc_image= (ImageView) Findviewbyid (r.id.vc_image); vc_image.setimagebitmap (Code.getinstance (). Getbitmap ()); vc_code= (EditText) Findviewbyid (R.id.vc_code); Getcode=code.getinstance (). GetCode (); Get the verification code shown LOG.E ("info", getcode+ "----"); vc_shuaixi= (Button) Findviewbyid (R.id.vc_shuaixi); vc_ Shuaixi.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method StubvC_image.setimagebitmap (Code.getinstance (). Getbitmap ()); Getcode=code.getinstance (). GetCode ();}); vc_ok= (Button) Findviewbyid (R.ID.VC_OK); Vc_ok.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated Method Stubstringv_code=vc_code.gettext (). toString (). Trim (); if (v_code==null| | V_code.equals (")) {Toast.maketext (" ") {mainactivity.this," No verification Code entered ", 2). Show (); else if (!v_code.equals (GetCode)) {Toast.maketext (Mainactivity.this, "The verification code is not filled in correctly", 2). Show (); Else{toast.maketext (Mainactivity.this, "Operation succeeded", 2). Show ();}});}


Finally, one of the classes required for CAPTCHA code:

Import Java.util.random;import Android.graphics.bitmap;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.bitmap.config;public class Code { private static final char[] CHARS = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G ', '  H ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' w ', ' x ', ' y ', ' z ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z '};p rivate static Code b Putil;private code () {};p ublic static code getinstance () {if (Bputil = = null) Bputil = new Code (); return bputil;} Default settingsprivate static final int default_code_length = 4;//The length of the verification code here is the 4 bit private static final int default_font_si ZE = 60;//Font size private static final int default_line_number = 3;//How many lines of interference private static final int base_padding_left = 20; Left margin private static final int range_padding_left = 35;//Left margin range value private staticFinal int base_padding_top = 42;//Top margin private static final int range_padding_top = 15;//Top margin range value private static final int DEFA Ult_width = 200;//default width. The total width of the picture private static final int default_height = 70;//default height. Total height of the picture private final int default_color=0xdf ;//default background color value//settings decided by the layout xml//canvas width and heightprivate int width = default_width;private int Heigh t = default_height; Random word space and pading_topprivate int base_padding_left = base_padding_left;private int range_padding_left = Range _padding_left;private int base_padding_top = base_padding_top;private int range_padding_top = RANGE_PADDING_TOP;// Number of chars, lines;  Font sizeprivate int codelength = default_code_length;private int line_number = default_line_number;private int font_size = Default_font_size;//variablesprivate String code;//Save generated verification code private int Padding_left, padding_top;private Random Random = new Random ();p rivate Bitmap CreateBitmap () {padding_left = 0; Bitmap BP = bitmap.createbitmap (width, height, COnfig. argb_8888); Canvas c = new canvas (BP); code = Createcode (); C.drawcolor (Color.rgb (Default_color, Default_color, Default_color)); Paint paint = new paint ();p aint.settextsize (font_size); for (int i = 0; i < code.length (); i++) {Randomtextstyle (paint); Randompadding (); C.drawtext (Code.charat (i) + "", Padding_left, Padding_top, paint);} for (int i = 0; i < Line_number; i++) {DrawLine (c, paint);} C.save (Canvas.all_save_flag);//Save C.restore ();//return BP;} Public String GetCode () {return code.tolowercase ();} Public Bitmap Getbitmap () {return CreateBitmap ();} Private String Createcode () {StringBuilder buffer = new StringBuilder (); for (int i = 0; i < codelength; i++) {Buffer.ap Pend (Chars[random.nextint (Chars.length));} return buffer.tostring ();}  private void DrawLine (canvas canvas, paint paint) {int color = Randomcolor (); int startX = Random.nextint (width); int Starty = Random.nextint (height); int stopx = Random.nextint (width); int stopy = random.nextint (height);p aint.setstrokewidth (1) ;p aint.SetColor (color); Canvas.drawline (StartX, Starty, stopx, stopy, paint);} private int Randomcolor () {return randomcolor (1);} private int Randomcolor (int rate) {int red = random.nextint/Rate;int green = Random.nextint (in)/rate;int blue = Random.nextint (Rate;return)/Color.rgb (red, green, blue);} private void Randomtextstyle (paint paint) {int color = Randomcolor ();p aint.setcolor (color);p Aint.setfakeboldtext (  Random.nextboolean ()); True is bold, false is non-bold float skewx = Random.nextint (one-by-one)/10;skewx = Random.nextboolean ()? SKEWX:-skewx;paint.settextskewx (SKEWX); Float type parameter, negative number indicates right oblique, integer left oblique//paint.setunderlinetext (true); True to underline, false to non-underscore//paint.setstrikethrutext (true); True for strikethrough, false for non-strikethrough}private void randompadding () {padding_left + = Base_padding_left + random.nextint (range_padding_ left);p adding_top = Base_padding_top + random.nextint (range_padding_top);}}


The code has been posted, you can try to do it!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.