Getting Started with Android Custom view

Source: Internet
Author: User
Tags getcolor

Introduction to view architecture:

In Android, controls exist primarily in the form of viewgroup and view. The ViewGroup control can contain more than one view control, which is responsible for the measurement and drawing of all child controls inside it, and for passing interactive events. ,

In mobile development for Android, each activity contains a Phonewindow object that sets Decorview to the root view of the application window. All listener events On this view are received through Windowmanagerservice and are onclicklistener back and forth through the activity. Decorview divides the screen into two parts, Titleview and Contentview, and our Setcontentview method is used to handle the layout display of the location. Our activity_main is in such a framelayout with the content of the ID.

Customizing the View Implementation

Customize the view process,

    1. Custom view initialization (creating classes, introducing custom attributes, etc.)
    2. View measurement (override onmeasure to get custom size and set)
    3. View drawing (overriding OnDraw for view)
    4. Setting a listener interface for a custom view
Measurement Measurespec of view

A 32-bit int value, the high 2 bits represent the measurement mode, the low 30 bits represent the measured size, and are used for the measurement of the auxiliary view, the mode is as follows:



UNSPECIFIED (Custom mode): Size setting No limit, it's a little bit of a drag, I think.

First must rewrite the Onmeasure method, as for why, the source of a wave

    @Override    protectedvoidonMeasure(intint heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }

In as in the ctrl+b to see the source of Onmeasure,

    protectedvoidonMeasure(intint heightMeasureSpec) {        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));    }

Obviously, the custom Measurespec object is passed as a parameter to setmeasureddimension.

And look at the role of Getdefaultsize.

 Public Static int getdefaultsize(intSizeintMEASURESPEC) {intresult = size;intSpecmode = Measurespec.getmode (Measurespec);intSpecsize = Measurespec.getsize (Measurespec);Switch(Specmode) { CaseMeasureSpec.UNSPECIFIED:result = size; Break; CaseMeasurespec.at_most: CaseMeasureSpec.EXACTLY:result = specsize; Break; }returnResult }

Getdefaultsize selects the corresponding size according to the corresponding measurement mode.

In the second parameter of the method, is a getsuggestedminimumwidth () or Getsuggestedminimumheight () method, taking Getsuggestedminimumwidth () as an example,

protectedintgetSuggestedMinimumWidth() {        returnnull) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());    }

The official explanation is: Returns the suggested minimum width, the view should use. This
Returns the maximum of the view ' s minimum width. The most suitable width was born like this, and

Because the view class supports exactly mode by default, in order to implement the wrapcontent of a custom view, you must use a different schema, that is, overriding the Onmeasure method.

In fact, Onmeasure rewrite is very simple, is through the measurespec provided by Google to get mode and size, then according to the obtained mode to select the XML data set, and then pass the data to setmeasureddimension.

    @Override    protected void onmeasure(intWidthmeasurespec,intHEIGHTMEASURESPEC) {//Get mode and size from Measurespec        intWidthmode = Measurespec.getmode (Widthmeasurespec);intWidthsize = Measurespec.getsize (Widthmeasurespec);intHeightmode = Measurespec.getmode (Heightmeasurespec);intHeightsize = Measurespec.getsize (Heightmeasurespec);intWidthintHeight;//To get preset width and height based on mode        if(Widthmode = = measurespec.exactly)        {width = widthsize; }Else{mpaint.settextsize (mtitletextsize); Mpaint.gettextbounds (Mtitletext,0, Mtitletext.length (), mbound);floatTextWidth = Mbound.width ();intdesired = (int) (Getpaddingleft () + TextWidth + getpaddingright ());        width = desired; }if(Heightmode = = measurespec.exactly)        {height = heightsize; }Else{mpaint.settextsize (mtitletextsize); Mpaint.gettextbounds (Mtitletext,0, Mtitletext.length (), mbound);floatTextHeight = Mbound.height ();intdesired = (int) (Getpaddingtop () + TextHeight + getpaddingbottom ());        height = desired; }///To pass our custom dataSetmeasureddimension (width, height); }
Drawing of view

For Android 2D Graphics, we mainly use the graphics package, which mainly includes the canvas class, the paint class, the color class and the bitmap class, and so on.

Drawing graphics must use color, in the Android development of the use of color and access to have questions to see this article: Color

Paint class

To draw a graphic, you first have to adjust the brush to set the relevant properties of the brush to your own development needs.

Setantialias: Sets the brush's jagged effect.
SetColor: Sets the brush color.
Setargb: Sets the a,r,p,g value of the brush.
Setalpha: Sets the alpha value.
Settextsize: Sets the font size.
SetStyle: Sets the brush style, hollow or solid.
Setstrokewidth: Sets the hollow border width.
GetColor: Gets the color of the brush.
Getalpha: Get the alpha value of the brush

See also: Paint detailed

Canvas class

Canvas, which we can call a canvas, can draw a variety of things on it, is the basis for Android 2D graphics, and needs to be set to paint before using this class.

Cnavas Drawing Reference:

In addition to basic drawing, canvas can also perform some basic operations. Displacement, scaling, rotation, tilt, and snapshots and rollbacks.

There is a need to see for yourself: basic operation of Canvas

A simple round-drawing example

Paint paint = new paint ();Paint. SetColor(Color. CYAN);Paint. Setstrokewidth(3);Paint. Setantialias(true);Hollow Paint. SetStyle(Paint. Style. STROKE);Canvas. Drawcircle( the, -, -, paint);Paint. SetStyle(Paint. Style. FILL);Canvas. Drawcircle( the, the, -, paint);
Custom properties

Custom Attribute Flow

    1. Customizing a CustomView Class
    2. Create the Attrs.xml file and add the required item and declare-styleable
    3. Reference the custom property in the layout file and initialize
    4. Get custom properties and their values through Typedarray in the constructor method in the CustomView class

The constructor of this class can have up to four parameters,

public void CustomView (context context) {}
public void CustomView (context context, AttributeSet attrs) {}
public void CustomView (context context, AttributeSet attrs, int defstyleattr) {}
public void CustomView (context context, AttributeSet attrs, int defstyleattr, int defstyleres) {}

In the construction method, the value name and value of all properties of the custom view are saved in AttributeSet, getting the Property code:

int count = attrs.getAttributeCount();        for (int0; i < count; i++) {            String attrName = attrs.getAttributeName(i);            String attrVal = attrs.getAttributeValue(i);            Log"attrName = "" , attrVal = " + attrVal);        }

In this way we can only get those attributes that are directly defined in the XML, such as android:text = "horzion" , but for example android:text = "@String/name" will directly feed you an ID code in the R file, in order to simplify the work here introduce Typearray.

TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView0);

At this point, the collection in the Typearray is simplified and can be used directly.

A complete example:

Public Customtitleview (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle);Get the custom style attributes that we defined TypedArray TypedArray = context. Gettheme(). Obtainstyledattributes(Attrs, R. Styleable. Customtitleview, Defstyle,0);int n = TypedArray. GetIndexCount();for (int i =0; i < n; i++){int attr = TypedArray. GetIndex(i);Switch (attr) {case R. Styleable. Customtitleview_titletext:mtitletext = TypedArray. getString(attr);                     Break;Case R. Styleable. Customtitleview_titletextcolor1://Default color set to black Mtitletextcolor = TypedArray. GetColor(attr, Color. BLACK);                     Break;Case R. Styleable. Customtitleview_titletextsize://default setting is -Sp,typevalue can also convert sp to px mtitletextsize = TypedArray. Getdimensionpixelsize(attr, (int) typedvalue. Applydimension(Typedvalue. COMPLEX_UNIT_SP, -, Getresources (). Getdisplaymetrics()));                     Break;}} TypedArray. Recycle();//Remember to recycle}

In addition, declare-styleable tags can tell the system that this is a custom property, but also help us to generate some constants in the R.java to facilitate our use.
Finally, after getting the required properties, we set it to the corresponding paint, create the paint and call the OnDraw method to redraw.

Use the Postinvalidate method to start drawing outside of the UI thread, and then use the Invalidate method to repaint directly in the UI thread when redrawing is required.
See also: The difference between postinvalidate and invalidate

Setting up the Listener interface

After customizing the view, it is common to expose some interfaces to control the state of the view, or to monitor changes in the view.
Directly in the CustomView construction method, you can set the monitoring event for the view

        //设置监听事件        this.setOnClickListener(new OnClickListener()        {            @Override            publicvoidonClick(View v)            {                mTitleText = randomText();                postInvalidate();            }        });

A small example of a verification code:

Source Address: Custom

The original learning Recyclerview, went to half found the custom split line has a lot of do not understand the place, so there is turned to re-learn custom view, see the space and development of art exploration, as well as the network blog many, and finally write enough of this foundation of the custom.
For more in-depth canvas learning, you can join this Daniel's last article, Canvas pictures and Zhang Hongyang Entire series of Custom view combat
The road long its repair far XI, I will go up and down and quest. Commemorate the first Markdown blog

Getting Started with Android Custom view

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.