Android Custom View write random verification code _android

Source: Internet
Author: User
Tags stringbuffer

A lot of Android Getting Started program apes may be more fearful about Android custom view, but this is the only way to get to the master's level, all ready to spend some time on custom view and write more articles. To summarize the steps for customizing the view first:
1. Customize View Properties
2, in the view of the construction method to get our custom attributes
[3, rewrite onmesure]
4. Rewrite OnDraw

I marked 3 with [], so saying 3 is not necessarily necessary, but in most cases it needs to be rewritten.

1. Custom View properties, first create a attrs.xml under res/values/, define our attributes inside and declare our entire style.

<?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= "Customtitleview" > 
 <attr name= "TitleText"/> <attr-name= 
 "Titletextcolor"/> 
 <attr name= "titletextsize"/> 
 </declare-styleable> 
 
</ Resources> 

We have defined the font, font color, font size 3 attributes, format is the value of this property type:
Altogether have: string,color,demension,integer,enum,reference,float,boolean,fraction,flag; not clear to Google.
And then declare our custom view in the layout.

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" 
 xmlns:tools= "http:// Schemas.android.com/tools " 
 xmlns:custom=" http://schemas.android.com/apk/res/com.example.customview01 
 " Android:layout_width= "Match_parent" 
 android:layout_height= "match_parent" > 
 
 < Com.example.customview01.view.CustomTitleView 
 android:layout_width= "200DP" 
 android:layout_height= " 100DP " 
 custom:titletext=" 3712 " 
 custom:titletextcolor=" #ff0000 " 
 custom:titletextsize=" 40sp "/> 
 
</RelativeLayout> 

Be sure to introduce xmlns:custom= "http://schemas.android.com/apk/res/com.example.customview01" our namespaces, The following package path refers to the package of the project

2, in the view of the construction method, get our custom style

/** * Text/private String mtitletext; 
 /** * Text color * * private int mtitletextcolor; 
 
 /** * Text Size * * private int mtitletextsize; 
 /** * When drawing Control of the scope of text drawing * * Private Rect Mbound; 
 
 Private Paint Mpaint; 
 Public Customtitleview (context, AttributeSet attrs) {This (context, attrs, 0); 
 The public Customtitleview {This (context, NULL); /** * get my custom style attributes * * @param context * @param attrs * @param defstyle/public Customtitleview (Contex 
 T context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); /** * Get the Custom style attribute we defined/TypedArray a = Context.gettheme (). Obtainstyledattributes (Attrs, R.styleable.customtitleview 
 , Defstyle, 0); 
 int n = a.getindexcount (); 
 for (int i = 0; i < n; i++) {int attr = A.getindex (i); 
 Switch (attr) {Case r.styleable.customtitleview_titletext:mtitletext = a.getstring (attr); 
 Break 
 Case R.styleable.customtitleview_titletextcolor:The default color is set to black Mtitletextcolor = A.getcolor (attr, Color.Black); 
 Break Case R.styleable.customtitleview_titletextsize://The default setting is 16sp,typevalue can also convert sp to px mtitletextsize = A.getdimensionpixelsize (attr, (int) typedvalue.applydimension (typedvalue.complex_unit_sp, Getresources (). 
 Getdisplaymetrics ())); 
 
 Break 
 
 } a.recycle (); 
 /** * Obtains the width and height of the drawn text/mpaint = new Paint (); 
 Mpaint.settextsize (mtitletextsize); 
 Mpaint.setcolor (Mtitletextcolor); 
 Mbound = new Rect (); 
 
 Mpaint.gettextbounds (mtitletext, 0, Mtitletext.length (), mbound); 
 }

We've rewritten 3 construction methods, the default layout file calls the construction of two parameters, so remember to let all the constructs call our three-parameter constructs, and we get our custom properties in the construction of three parameters.

3, we rewrite the ondraw,onmesure call system provided:

@Override 
 protected void onmeasure (int widthmeasurespec, int heightmeasurespec) 
 { 
 super.onmeasure ( Widthmeasurespec, Heightmeasurespec); 
 
 @Override 
 protected void OnDraw (Canvas Canvas) 
 { 
 mpaint.setcolor (color.yellow); 
 Canvas.drawrect (0, 0, getmeasuredwidth (), Getmeasuredheight (), mpaint); 
 
 Mpaint.setcolor (Mtitletextcolor); 
 Canvas.drawtext (Mtitletext, getwidth ()/2-mbound.width ()/2, GetHeight ()/2 + mbound.height ()/2, mpaint); 
  

The effect at this point is:

is not a good feeling, basically has implemented a custom view. But at this point, if we write the width and height of the layout file as Wrap_content, we will find that the effect is not our expectation:

The system helps us measure the height and width is match_parnet, when we set the clear width and height, the system helps us to measure the result is the result that we set, when we set to Wrap_content, or Match_ The parent system helps us measure the result is the length of the match_parent.
So when Wrap_content is set, we need to measure ourselves, that is, to rewrite the Onmesure method:
Before rewriting, understand Measurespec's specmode, altogether three types:

exactly: usually set a definite value or a match_parent
At_most: indicates that the child layout is restricted to a maximum value, typically warp_content
UNSPECIFIED: indicates how big the child layout wants, and is rarely used

Here's how we rewrite the Onmeasure code:

@Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {int widthmode = Measurespec.getmode 
 (WIDTHMEASURESPEC); 
 int widthsize = measurespec.getsize (Widthmeasurespec); 
 int heightmode = Measurespec.getmode (Heightmeasurespec); 
 int heightsize = measurespec.getsize (Heightmeasurespec); 
 int width; 
 int height; 
 if (Widthmode = = measurespec.exactly) {width = widthsize; 
 else {mpaint.settextsize (mtitletextsize); 
 Mpaint.gettextbounds (mtitle, 0, Mtitle.length (), mbounds); 
 float textWidth = Mbounds.width (); 
 int desired = (int) (Getpaddingleft () + TextWidth + getpaddingright ()); 
 width = desired; 
 } if (Heightmode = = measurespec.exactly) {height = heightsize; 
 else {mpaint.settextsize (mtitletextsize); 
 Mpaint.gettextbounds (mtitle, 0, Mtitle.length (), mbounds); 
 float textHeight = Mbounds.height (); 
 int desired = (int) (Getpaddingtop () + TextHeight + getpaddingbottom ()); 
 height = desired; } setmeasureddimenSion (width, height); 

 }

Now we modify the layout file:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" 
 xmlns:tools= "http:// Schemas.android.com/tools " 
 xmlns:custom=" http://schemas.android.com/apk/res/com.example.customview01 
 " Android:layout_width= "Match_parent" 
 android:layout_height= "match_parent" > 
 
 < Com.example.customview01.view.CustomTitleView 
 android:layout_width= "wrap_content" 
 android:layout_ height= "Wrap_content" 
 custom:titletext= "3712" 
 android:padding= "10DP" 
 custom:titletextcolor= "# ff0000 " 
 android:layout_centerinparent=" true " 
 custom:titletextsize=" 40sp "/> 
 
</ Relativelayout> 

Now the effect is:

Fully compound our expectations, now we can be the height, width of casual settings, basically can meet our needs.
Of course, this custom view doesn't have a lot of advantages over TextView, and all we feel is adding an event to the custom view:
To add in construction:

This.setonclicklistener (New Onclicklistener () 
 { 
 
 @Override public 
 void OnClick (View v) 
 { 
 Mtitletext = Randomtext (); 
 Postinvalidate (); 
 } 
 
 ); 
Private String Randomtext () 
 { 
 Random Random = new Random (); 
 set<integer> set = new Hashset<integer> (); 
 while (Set.size () < 4) 
 { 
 int randomint = Random.nextint (a); 
 Set.add (Randomint); 
 } 
 StringBuffer sb = new StringBuffer (); 
 for (Integer I:set) 
 { 
 sb.append ("" + i); 
 } 
 
 return sb.tostring (); 
 } 

To run the following:

We added a click event, each time it randomly generated a 4-bit random number, interested in the OnDraw can add a bit of noise, and then rewritten as a verification code, is not a good feeling.

SOURCE Download: Http://xiazai.jb51.net/201610/yuanma/AndroidCustomView (jb51.net). rar

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.

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.