Android Custom View implementation Random verification code _android

Source: Internet
Author: User
Tags abs drawtext int size stringbuffer

Customizing view is a more important skill for Android development, so writing a custom view primer here is a relatively simple feature for generating random validation code:
Custom view is mainly divided into several steps
1. Customize View Properties
2. Get custom properties in our custom layout
3. Rewrite the Onmesure method
4. Rewrite the OnDraw method
Okay, now we're going to step through it, create our view property first
Create a Attrs.xml file in the Valuse directory, and then:

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
 <attr name= "textcolor" format= "Color" >
 <attr name= "textcontent" format= "string"/> <attr name=
 "textsize" format= "Dimension"/>

 <declare-styleable name= "Verificationcodeview" >
 <attr name= "textcontent"/> <attr
 Name = "TextColor"/>
 <attr name= "textsize"/>
 </declare-styleable>
</resources>

We've defined a total of three attributes, one is color, content, size

And then we're going to build our custom class.

public class Verificationcodeview extends View {/** * text/private String mtitletext;
 /** * Text color * * private int mtextcolor;

 /** * Text Size * * private int mtextsize;
 /** * When drawing Control of the scope of text drawing * * Private Rect Mbound;
 /** * Initialization brush/private Paint mtextpaint;
 Private Paint Mpointpaint;
 Private Paint Mpathpaint;
 /** * Interference Point coordinate set * * Private arraylist<pointf> mpoints = new arraylist<pointf> ();

 /** * Draw a set of paths for Bezier curves/private arraylist<path> mpaths = new arraylist<path> ();
 Public Verificationcodeview {This (context, NULL);
 Public Verificationcodeview (context, AttributeSet AttributeSet) {This (context, AttributeSet, 0); Public Verificationcodeview (context, AttributeSet attributeset, int defstyle) {Super (context, AttributeSet,
 Defstyle); TypedArray TypedArray = Context.gettheme (). Obtainstyledattributes (AttributeSet, R.styleable.verificationcodeview,
 Defstyle, 0); int size = Typedarray.getindexcount ();
 for (int i = 0; i < size; i++) {int content = Typedarray.getindex (i);
   Switch (content) {Case r.styleable.verificationcodeview_textcontent:mtitletext = typedarray.getstring (content);
  Break
   Case R.styleable.verificationcodeview_textcolor:mtextcolor = typedarray.getcolor (content, Color.Black);
  Break Case R.styleable.verificationcodeview_textsize://The default setting is 16sp,typevalue can also convert sp to px mtextsize = Typedarray.getdimensio Npixelsize (content, (int) typedvalue.applydimension (typedvalue.complex_unit_sp, Getresources ().
   Getdisplaymetrics ()));
  Break
 } typedarray.recycle (); Set Click event Transform Digital This.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View v) {Mtitletext = R
  Andomtext ();
  Postinvalidate ();
 }
 }); 
 /** * Exactly: generally set a definite value or match_parent * At_most: Indicates that the child layout is restricted to a maximum value, generally warp_content * UNSPECIFIED: Indicates how large the child layout wants, and is rarely used * * @param widthmeasurespec * @param heightmeasurespec/@Override protected void OnmeaSure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec, Heightmeasurespec);
 int widthmode = Measurespec.getmode (Widthmeasurespec);
 int widthsize = measurespec.getsize (Widthmeasurespec);
 int heightmode = Measurespec.getmode (Heightmeasurespec);
 int heightsize = measurespec.getsize (Heightmeasurespec); Use to set the size of the layout to be drawn if (Widthmode!= measurespec.exactly) {widthsize = (int) (Getpaddingleft () + mbound.width () + Getpaddin
 Gright ()); } if (Heightmode!= measurespec.exactly) {heightsize = (int) (Getpaddingtop () + mbound.height () + Getpaddingbottom ())
 ;
 } setmeasureddimension (Widthsize, heightsize);
 @Override protected void OnDraw (Canvas Canvas) {//Generate a random background color mtextpaint.setcolor (color.yellow);
 Canvas.drawrect (0, 0, getmeasuredwidth (), Getmeasuredheight (), mtextpaint);
 Generate a random text color mtextpaint.setcolor (mtextcolor); Draw the text in the middle of the layout canvas.drawtext (Mtitletext, getwidth ()/2-mbound.width ()/2, GetHeight ()/2 + mbound.height ()/2, Mtex TpainT);
 /** * Generates a random four-bit numeric verification code * * @return/private String Randomtext () {Random Random = new Random ();
 set<integer> set = new hashset<integer> ();
  while (Set.size () < 4) {int randomint = Random.nextint (10);
 Set.add (Randomint);
 StringBuffer sb = new StringBuffer ();
 for (Integer i:set) {sb.append ("" + i);
 return sb.tostring ();

 }
}

The above code is the custom class, inherits the view he has three constructs method, we want to obtain its property, therefore must go third, but the default is the second, so we have to call the third one inside each, to ensure that the initialization work attention It is called using the constructor method of this, not the super
When our class comes out, the back is very simple.

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android=
"http://schemas.android.com/apk" /res/android "
 xmlns:verification=" Http://schemas.android.com/apk/res-auto "
 android:layout_width=" match _parent "
 android:layout_height=" match_parent "
 android:gravity=" center "
 >

 < Com.example.aotuman.verification.view.VerificationCodeView
 android:layout_width= "Wrap_content"
 android:layout_height= "Wrap_content"
 android:paddingtop= "10DP"
 android:paddingbottom= "10DP"
 android:paddingleft= "10DP"
 android:paddingright= "10DP"
 verification:textcontent= "3712"
 Verification:textcolor= "#ff0000"
 verification:textsize= "40sp"/>
</RelativeLayout>

You can use it in the layout, xmlns:verification= "Http://schemas.android.com/apk/res-auto" is required, or you cannot find a custom attribute.

Well, that's the easiest thing to accomplish.

The next step is to implement the OnDraw () method of drawing some scatter points and curves and modifying our custom class.

@Override protected void OnDraw (Canvas Canvas) {initdata ();
 Random mrandom = new Random ();
 Generate a random background color Mtextpaint.setargb (255, Mrandom.nextint +, Mrandom.nextint (200) + 20);
 Canvas.drawrect (0, 0, getmeasuredwidth (), Getmeasuredheight (), mtextpaint);
 Generate random text color Mtextpaint.setargb (255, Mrandom.nextint +, Mrandom.nextint (+) +, Mrandom.nextint (200) + 20); Draw the text in the middle of the layout canvas.drawtext (Mtitletext, getwidth ()/2-mbound.width ()/2, GetHeight ()/2 + mbound.height ()/2, Mtex

 Tpaint); Interference effect 1--interference point for (PointF pointf:mpoints) {Mpointpaint.setargb (255, Mrandom.nextint () +, Mrandom.nextint (2
  +, Mrandom.nextint (200) + 20);
 Canvas.drawpoint (pointf.x, POINTF.Y, Mpointpaint);  //Interference effect 2--interference line for (Path path:mpaths) {Mpathpaint.setargb (255, Mrandom.nextint () +, Mrandom.nextint (200)
  + Mrandom.nextint (200) + 20);
 Canvas.drawpath (path, mpathpaint); private void InitData () {Random Mrandom = new Random ();
 Gets the width and height of the control, which is now measured to complete int mheight = GetHeight ();
 int mwidth = GetWidth ();
 Mpoints.clear (); Generate the interference point coordinates for (int i = 0; i < i++) {PointF PointF = new PointF (Mrandom.nextint (mwidth) + mrandom.nextint (
  Mheight) + 10);
 Mpoints.add (PointF);
 } mpaths.clear ();
  Generate interference line coordinates for (int i = 0; i < 2; i++) {Path PATH = new Path ();
  int startx = Mrandom.nextint (MWIDTH/3) + 10;
  int starty = Mrandom.nextint (MHEIGHT/3) + 10;
  int endx = Mrandom.nextint (MWIDTH/2) + MWIDTH/2-10;
  int EndY = Mrandom.nextint (MHEIGHT/2) + MHEIGHT/2-10;
  Path.moveto (StartX, starty);
  Path.quadto (Math.Abs (ENDX-STARTX)/2, Math.Abs (Endy-starty)/2, EndX, EndY);
 Mpaths.add (path);
 } private void Init () {//init text Brush/** * Gets the width and height of the drawn text/mtextpaint = new Paint ();

 Mtextpaint.settextsize (mtextsize);
 Mbound = new Rect ();
 Acquired into existence Mbound inside Mtextpaint.gettextbounds (mtitletext, 0, Mtitletext.length (), mbound); Initialization interference Point Brush Mpointpaint = new PaiNT ();
 Mpointpaint.setstrokewidth (6); Mpointpaint.setstrokecap (Paint.Cap.ROUND);
 Set the breakpoint at the circle//initialization interference line brush Mpathpaint = new Paint ();
 Mpathpaint.setstrokewidth (5);
 Mpathpaint.setcolor (Color.gray); Mpathpaint.setstyle (Paint.Style.STROKE); Set the brush to a hollow mpathpaint.setstrokecap (Paint.Cap.ROUND);

 Set Breakpoint at Circle}

The init () method is added to the construction method.
Ok so far to complete, and then we use as long as the transplant can be, how, also very simple

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.