Android Verification Code implementation, detailed labeling!

Source: Internet
Author: User

Reprint please indicate the source: Wang 亟亟 's way of Daniel

The last blog post wrote a generation of two-dimensional code, this one to a random number.
Package Directory

Operating effect:

is to draw a bunch of things and put them in ImageView.
Words do not say more directly on the code:

 Public  class mainactivity extends Activity {ProgressDialog Mloadingdialog;    Button Showcaptchad;    ImageView ImageView; Bitmap Validatecodeimage;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        imageview= (ImageView) Findviewbyid (R.id.imageview);        Showcaptchad= (Button) Findviewbyid (R.id.showcaptchad); Showcaptchad.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {Showloadingdialog ("Loading ...");//Recycling bitmap                if(NULL! = Validatecodeimage &&!validatecodeimage.isrecycled ()) {validatecodeimage.recycle (); Validatecodeimage =NULL; }//Generate picturesValidatecodeimage =makevalidatecode ( $, -);                Imageview.setimagebitmap (Validatecodeimage); Toast.maketext (mainactivity. This,"Verification Code generation succeeded"+"Verification Code is"+gainvalidatecodevalue (), Toast.length_short). Show ();            Dismissloadingdialog ();    }        }); }/ * Show dialog box * /     Public void Showloadingdialog(String msg) {if(Mloadingdialog! =NULL&& mloadingdialog.isshowing ()) {return; } Mloadingdialog =NewProgressDialog ( This); Mloadingdialog.setmessage (msg);//Mloadingdialog.setonkeylistener (Monkeylistener);        //Mloadingdialog.setcancelable (false);Mloadingdialog.show (); }/** * Cancel Load dialog box * /     Public void Dismissloadingdialog() {if(Mloadingdialog! =NULL) {Mloadingdialog.dismiss (); }    }@Override     Public Boolean Oncreateoptionsmenu(Menu menu) {//inflate the menu; This adds items to the action bar if it is present.Getmenuinflater (). Inflate (R.menu.main, menu);return true; }@Override     Public Boolean onoptionsitemselected(MenuItem Item) {//Handle Action Bar item clicks here. The Action Bar would        //automatically handle clicks on the Home/up button, so long        //As you specify a parent activity in Androidmanifest.xml.        intid = item.getitemid ();if(id = = r.id.action_settings) {return true; }return Super. onoptionsitemselected (item); }/** * Get captcha Picture * @param Width Verification code Width * @param Height Verification code Height * @return Verification Code BITMA P Object * /     Public synchronized StaticBitmapMakevalidatecode(intWidthintHeight) {returnValidatecodegenerator.createbitmap (width, height); }/** * Get Verification code value * @return captcha string */     Public synchronized StaticStringGainvalidatecodevalue(){returnValidatecodegenerator.getcode (); }/** * Randomly generated verification code inner class * * /    Final StaticClass validatecodegenerator{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 ',        };//default Settings        Private Static Final intDefault_code_length =4;Private Static Final intDefault_font_size = -;Private Static Final intDefault_line_number =3;//number of lines of clutter        Private Static Final intBase_padding_left = the, Range_padding_left =Ten, Base_padding_top = *, Range_padding_top = -;Private Static Final intDefault_width = -, Default_height = -;//variables        Private StaticString value;Private Static intPadding_left, Padding_top;Private StaticRandom random =NewRandom (); Public StaticBitmapCreateBitmap(intWidthintHeight) {Padding_left =0;//Create canvasBitmap BP = bitmap.createbitmap (width, height, config.argb_8888); Canvas C =NewCanvas (BP);//randomly generate CAPTCHA charactersStringBuilder buffer =NewStringBuilder (); for(inti =0; i < default_code_length;            i++) {buffer.append (Chars[random.nextint (chars.length)]); } value = Buffer.tostring ();//Set colorC.drawcolor (Color.White);//Set Brush sizePaint paint =NewPaint (); Paint.settextsize (default_font_size); for(inti =0; I < value.length (); i++) {//Random styleRandomtextstyle (paint);                Padding_left + = Base_padding_left + random.nextint (range_padding_left);                Padding_top = Base_padding_top + random.nextint (range_padding_top); C.drawtext (Value.charat (i) +"", Padding_left, padding_top, paint); } for(inti =0; i < Default_line_number;            i++) {DrawLine (c, paint); }//SaveC.save (Canvas.all_save_flag); C.restore ();returnbp } Public StaticStringGetCode() {returnValue }Private Static void Randomtextstyle(Paint paint) {intcolor = Randomcolor (1);            Paint.setcolor (color); Paint.setfakeboldtext (Random.nextboolean ());//true is bold, false is not bold            floatSkewx = Random.nextint ( One) /Ten; Skewx = Random.nextboolean ()?            SKEWX:-skewx; Paint.settextskewx (SKEWX);//float type parameter, negative number for right oblique, integer left obliquePaint.setunderlinetext (true);//true is underlined, false is non-underlinedPaint.setstrikethrutext (true);//true for Strikethrough, false for non-strikethrough}Private Static void DrawLine(Canvas canvas, paint paint) {intcolor = Randomcolor (1);intStartX = Random.nextint (default_width);intStarty = Random.nextint (default_height);intSTOPX = Random.nextint (default_width);intStopy = Random.nextint (default_height); Paint.setstrokewidth (1);            Paint.setcolor (color);        Canvas.drawline (StartX, Starty, stopx, stopy, paint); }Private Static int Randomcolor(intRate) {intRed = Random.nextint ( the)/rate;intGreen = Random.nextint ( the)/rate;intBlue = Random.nextint ( the)/rate;returnColor.rgb (red, green, blue); }    }@Override    protected void OnDestroy() {//TODO auto-generated method stub    Super. OnDestroy ();if(NULL! = Validatecodeimage &&!validatecodeimage.isrecycled ()) {validatecodeimage.recycle (); Validatecodeimage =NULL;    } System.GC (); }}

Layout file:

<Relativelayout xmlns:android="Http://schemas.android.com/apk/res/android"    Xmlns:tools="Http://schemas.android.com/tools"    Android:layout_width="Match_parent"    Android:layout_height="Match_parent"    Android:paddingbottom="@dimen/activity_vertical_margin"    Android:paddingleft="@dimen/activity_horizontal_margin"    Android:paddingright="@dimen/activity_horizontal_margin"    Android:paddingtop="@dimen/activity_vertical_margin"    Tools:context="Com.example.captchademo.MainActivity">    <buttonandroid:id="@+id/showcaptchad"android:layout_width="Wrap _content "android:layout_height=" Wrap_content "android:layout_alignparenttop ="true"android:layout_centerhorizontal="true"android:text=" Showcaptchad " />                                                    <ImageViewandroid:id= "@+id/imageview"android:layout_width=" 200DP "android:layout_height="wrap_content "android:layout_below=" @+id/ Showcaptchad "android:layout_centerhorizontal=" true "android:minheight= "150DP" />                                                </relativelayout>

You can manipulate properties in an internal class if you want to modify them.
Source Address: Http://yunpan.cn/cd8R7TMTtWDwq access password 8a95

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Verification Code implementation, detailed labeling!

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.