Android Custom View (custom control)

Source: Internet
Author: User

First, create a control class indirectly or directly inherit the view class

Second, create a custom style attribute in the Attr.xml file, such as

<?XML version= "1.0" encoding= "Utf-8"?><Resources>    <attrname= "TitleText"format= "string" />    <attrname= "Titletextcolor"format= "Color" />    <attrname= "Titletextsize"format= "Dimension" />    <declare-styleablename= "Customtitleview">        <attrname= "TitleText" />        <attrname= "Titletextcolor" />        <attrname= "Titletextsize" />    </declare-styleable></Resources>

Iii. Implementing related logic in the control class

1, overloading three construction methods

Public Customtitleview (context context, AttributeSet attrs)

Public Customtitleview (Context context)

Public Customtitleview (context context, AttributeSet attrs, int defstyle)

2, in the construction of the style properties, similar to the control style in WP

TypedArray a = Context.gettheme (). Obtainstyledattributes (Attrs, R.styleable.customtitleview, Defstyle, 0);

In terms of construction, you can do some initialization operations.

3, overload Onmeasure method to measure the control, and the logic of WP exactly the same

protected void onmeasure (int widthmeasurespec, int heightmeasurespec)

4. Heavy-duty OnDraw method drawing screen

protected void OnDraw (canvas canvas)

Canvas is the canvas object of the control, where you can draw or add the content or other controls that you need to display on the canvas.

Iv. use on layout

1. When using attributes, you need to add a reference to the space

Xmlns:custom= "Http://schemas.android.com/apk/res/com.example.asdlon.customviewdemo"

2. Adding controls

    < Com.example.asdlon.customviewdemo.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 "/>

ImportJava.util.HashSet;ImportJava.util.Random;ImportJava.util.Set;ImportAndroid.content.Context;ImportAndroid.content.res.TypedArray;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Color;ImportAndroid.graphics.Paint;ImportAndroid.graphics.Rect;ImportAndroid.util.AttributeSet;ImportAndroid.util.TypedValue;ImportAndroid.view.View; Public classCustomtitleviewextendsview{/*** Text*/    PrivateString Mtitletext; /*** Color of text*/    Private intMtitletextcolor; /*** Size of text*/    Private intmtitletextsize; /*** Control the range of text drawing when drawing*/    PrivateRect Mbound; PrivatePaint Mpaint;  PublicCustomtitleview (Context context, AttributeSet attrs) { This(context, Attrs, 0); }     PublicCustomtitleview (Context context) { This(Context,NULL); }    /*** get my own custom style attributes * *@paramContext *@paramAttrs *@paramDefstyle*/     PublicCustomtitleview (context context, AttributeSet attrs,intDefstyle) {        Super(context, attrs, Defstyle); /*** Get the custom style attributes we've defined*/TypedArray a= Context.gettheme (). Obtainstyledattributes (Attrs, R.styleable.customtitleview, Defstyle, 0); intn =A.getindexcount ();  for(inti = 0; I < n; i++)        {            intattr =A.getindex (i); Switch(attr) { CaseR.styleable.customtitleview_titletext:mtitletext=a.getstring (attr);  Break;  CaseR.styleable.customtitleview_titletextcolor://The default color is set to blackMtitletextcolor =A.getcolor (attr, Color.Black);  Break;  Caser.styleable.customtitleview_titletextsize://The default setting is 16sp,typevalue can also convert SP to PXMtitletextsize = A.getdimensionpixelsize (attr, (int) typedvalue.applydimension (typedvalue.complex_unit_sp,16, Getresources (). Getdisplaymetrics ());  Break;        }} a.recycle (); /*** Get the width and height of the drawn text*/Mpaint=NewPaint ();        Mpaint.settextsize (mtitletextsize); //Mpaint.setcolor (mtitletextcolor);Mbound =NewRect (); Mpaint.gettextbounds (Mtitletext,0, Mtitletext.length (), mbound);  This. Setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {Mtitletext=Randomtext ();            Postinvalidate ();    }        }); }    PrivateString Randomtext () {random random=NewRandom (); Set<Integer> set =NewHashset<integer>();  while(Set.size () < 4)        {            intRandomint = Random.nextint (10);        Set.add (Randomint); } stringbuffer SB=NewStringBuffer ();  for(Integer i:set) {sb.append ("" +i); }        returnsb.tostring (); } @Overrideprotected voidOnmeasure (intWidthmeasurespec,intHeightmeasurespec) {        //super.onmeasure (Widthmeasurespec, heightmeasurespec);        intwidth = 0; intHeight = 0; /*** Set Width*/        intSpecmode =Measurespec.getmode (WIDTHMEASURESPEC); intSpecsize =measurespec.getsize (WIDTHMEASURESPEC); Switch(specmode) { Casemeasurespec.exactly://explicitly specified thewidth = getpaddingleft () + getpaddingright () +specsize;  Break;  CaseMeasurespec.at_most://generally for warp_contentwidth = getpaddingleft () + getpaddingright () +mbound.width ();  Break; }        /*** Set Height*/Specmode=Measurespec.getmode (HEIGHTMEASURESPEC); Specsize=measurespec.getsize (HEIGHTMEASURESPEC); Switch(specmode) { Casemeasurespec.exactly://explicitly specified theHeight = getpaddingtop () + getpaddingbottom () +specsize;  Break;  CaseMeasurespec.at_most://generally for warp_contentHeight = getpaddingtop () + getpaddingbottom () +mbound.height ();  Break;    } setmeasureddimension (width, height); } @Overrideprotected voidOnDraw (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); }}

Reference: http://blog.csdn.net/lmj623565791/article/details/24252901

Android Custom View (custom control)

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.