Android custom Controls deep learning Android Generate random Captcha _android

Source: Internet
Author: User

The properties of custom controls are described in the previous article, as detailed in the detailed Android custom control properties Typedarray and Attrs. then on this basis to implement the random verification code generation, inside the code is the custom control and involves the custom view painting.
1, first look at the implementation of the effect chart


It's OK to see this effect picture. Then look at the source code bar.
2, attr documents

<?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 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_co" Ntent "> <com.example.authcodeview.view.authcodeview android:id=" @+id/authcodeview "Android:layout_widt 
   H= "Wrap_content" android:layout_height= "wrap_content" android:padding= "10DP" authcodeview:titletext= "3712" Authcodeview:titletextcolor= "#00ffff" authcodeview:titletextsize= "40sp"/> <textview android:layout_wi 
 
 Dth= "Wrap_content" android:layout_height= "wrap_content" android:text= "click on the verification code, change a"/> </LinearLayout> <linearlayout android:layout_width= "Match_parent" android:layout_height= "Wrap_content" > <textview android:layout_width= "wrap_content" Android:layout_heig ht= "wrap_content" android:text= "Input verification Code"/> <edittext android:id= "@+id/edittext1" Android:layout_widt H= "Match_parent" android:layout_height= "Wrap_content" android:ems= "ten" android:inputtype= "number" > & Lt;requestfocus/> </EditText> </LinearLayout> <button android:id= "@+id/button1" Android: 
 Layout_width= "Match_parent" android:layout_height= "Wrap_content" android:text= "Authentication"/> </LinearLayout>

4, Custom Authcodeview.class
Inherit view, rewrite the

onmeasure (int widthmeasurespec, int heightmeasurespec)

OnDraw (Canvas Canvas) method.
Look at the code and have a detailed comment.

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 {//Points set public static final int point_num = 100; 
 Number of segments set public static final int line_num = 2; 
 Text private String Mtitletext; 
 The color of the text is private int mtitletextcolor; 
  
 The size of the text is private int mtitletextsize; 
 string[] Mchecknum = new String[4]; 
  
 Random Random = new Random (); 
 Control the range of text rendering when drawing private Rect mbound; 
 
 Private Paint Mpaint; 
 Public Authcodeview (context, AttributeSet attrs) {This (context, attrs, 0); 
 The public Authcodeview {This (context, NULL); }/** * get my own setThe semantic style attribute * * @param context * @param attrs * @param defstyle/public Authcodeview, Attrib 
  Uteset attrs, int defstyle) {Super (context, attrs, Defstyle); /** * Get the Custom style attribute we defined/TypedArray a = Context.gettheme (). Obtainstyledattributes (Attrs, R.styleable.authcodevi 
   
  EW, Defstyle, 0); 
  Gets a number of int n = a.getindexcount () for the Declare-styleable property named Authcodeview under the attr file. 
   for (int i = 0; i < n; i++) {int attr = A.getindex (i); Switch (attr) {//This property can not be, because all are randomly generated case r.styleable.authcodeview_titletext:mtitletext = a.getstring (att 
    R); 
   Break 
    Case R.styleable.authcodeview_titletextcolor://Default color set to Black Mtitletextcolor = A.getcolor (attr, Color.Black); 
   Break Case R.styleable.authcodeview_titletextsize://The default setting is 16sp,typevalue can also convert sp to px mtitletextsize = A.GETDIMENSIONPI Xelsize (attr, (int) typedvalue.applydimension (typedvalue.complex_unit_sp, Getresources (). GetdisPlaymetrics ())); 
 
   Break 
   
  } a.recycle (); 
 
  Mtitletext = Randomtext (); 
  /** * Obtains the width and height of the drawn text/mpaint = new Paint (); 
  Mpaint.settextsize (mtitletextsize); 
  Mbound = new Rect (); 
 
  Mpaint.gettextbounds (mtitletext, 0, Mtitletext.length (), mbound);  This.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Mtitletext = 
    Randomtext (); 
   Postinvalidate (); 
 
 } 
 
  }); 
  ///Randomly generate authentication code 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 (); 
 //Get Authentication Code public String Getauthcode () {return mtitletext; 
//Override this method to set the size of the custom view control @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {  Super.onmeasure (Widthmeasurespec, Heightmeasurespec); 
  int width = 0; 
 
  int height = 0; 
  /** * Set Width */int specmode = Measurespec.getmode (Widthmeasurespec); 
  int specsize = measurespec.getsize (Widthmeasurespec); 
   Switch (specmode) {case measurespec.exactly://explicitly specifies the width = getpaddingleft () + getpaddingright () + specsize; 
  Break 
   Case measurespec.at_most://is generally warp_content width = getpaddingleft () + getpaddingright () + mbound.width (); 
  Break 
  /** * Set Height * * Specmode = Measurespec.getmode (Heightmeasurespec); 
  Specsize = Measurespec.getsize (Heightmeasurespec); 
   Switch (specmode) {case measurespec.exactly://explicitly specifies the height = getpaddingtop () + getpaddingbottom () + specsize; 
  Break 
   Case measurespec.at_most://is generally warp_content height = getpaddingtop () + getpaddingbottom () + mbound.height (); 
  Break 
 
 } setmeasureddimension (width, height); } @Override protected void OnDraw (CanvasCanvas) {//Draw background color mpaint.setcolor (color.blue); 
   
  Canvas.drawrect (0, 0, getmeasuredwidth (), Getmeasuredheight (), mpaint); 
  Crossed Mpaint.setcolor (Mtitletextcolor); 
  int [] line; 
   for (int i = 0; i < line_num i + +) {//Set line width mpaint.setstrokewidth (5); 
   line = Getline (Getmeasuredheight (), Getmeasuredwidth ()); 
  Canvas.drawline (Line[0], line[1], line[2], line[3], mpaint); 
  //Draw dot int [] point; 
  int randomint; 
   for (int i = 0; i < point_num i + +) {//random fetch point size Randomint = Random.nextint (5); 
   Point = GetPoint (Getmeasuredheight (), Getmeasuredwidth ()); 
  Canvas.drawcircle (Point[0], point[1], randomint, mpaint); 
  //Draw Text int dx = 20 on validation control; 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); 
  ///Calculate the plot Y-point position of the verification Code private int Getpositon (int height) {int temppositoin = (int) (Math.random () * height); 
  if (Temppositoin <) {Temppositoin = 20; 
 return temppositoin; 
  The center point coordinates of the randomly generated point are public static int[] GetPoint (int height, int width) {int[] Tempchecknum = {0, 0, 0, 0}; 
  TEMPCHECKNUM[0] = (int) (Math.random () * width); 
  TEMPCHECKNUM[1] = (int) (Math.random () * height); 
 return tempchecknum;  
  The starting point coordinates and the end point coordinates public static int[] getline (int height, int width) {int[] Tempchecknum = {0, 0, 0, 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, how to use this custom Authcodeview package Com.example.authcodeview in mainactivity; 
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 = (Edi 
   Ttext) Findviewbyid (R.ID.EDITTEXT1); 
   String codestring = Edittext.gettext (). toString (). Trim (); if (Codestring.equals (Mauthcodeview.getauthcode ())) {Toast.maketext (this, "Verify code is correct!") 
   ", Toast.length_long). Show (); }else {Toast.maketext (this, "Authentication code Error!) 
   ", Toast.length_long). Show (); } break; 
  Default:break; 
 } 
   
 } 
 
 
}

SOURCE Download:Android generated random verification code demo

The above is the entire content of this article, I hope to help you learn.

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.