On Android Custom View

Source: Internet
Author: User

when we encounter native components in development that cannot meet our needs, we should write custom view at this time to meet some special component requirements.

Custom View

The concept of a personal summary of custom view is divided into two categories:
1, in the same style of the control group to use more than one, we can use the native control to combine a view for other places to call, reduce duplication of code.
To give a chestnut: the most common blank hint page, is generally the above is the icon below is the text can consider the above way. Directly below the code:

/*** We here because is blank hint page, upper and lower structure, so we choose is Linearlayout*/<span style= "font-size:18px;" >public class Navigationview extends LinearLayout {private ImageView iv_nva;private TextView tv_nva_title;public Nulldateview (Context context) {super (context); Layoutinflater Inflater = (layoutinflater) context.getsystemservice (Context.layout_inflater_service); Inflater.inflate (r.layout.view_nulldate, this);//Refer to the XML layout file you wrote Tv_nva_title = (TextView) Findviewbyid (R.id.tv_nva_ title); Iv_nva = (ImageView) Findviewbyid (R.ID.IV_NVA);} /** so that we can pass in different parameters, implement different display blank hint page */public void setData (int ivid,string title) {Tv_nva_title.settext (title); iv_ Nva.set.setImageResource (Ivid);}} </span>

2, this is relatively complex, but this way more custom, completely controlled by you, the control can be drawn to any style you want.
In general, simply rewrite the two functions: Onmeasure (), OnDraw ().
The onmeasure is responsible for measuring the dimensions of the current view.
OnDraw is responsible for drawing the current view.

You have to write at least 2 constructors:

<span style= "FONT-SIZE:18PX;" >public MyView (Context context) {   super (context);} Public MyView (context context, AttributeSet Attrs) {   Super (context, attrs);} </span>

To override the onmeasure method:
protected void onmeasure (int widthmeasurespec, int heightmeasurespec)
The widthmeasurespec and heightmeasurespec in the parameters contain wide and high information, and also include measurement modes.
In other words, an int integer with the measurement mode and size in it, let's explain why an int can hold two messages at a time.
So how does Google put an int in both the measurement mode and the size information? We know that the int data takes up 32 bits, and Google realizes that the first 2 bits of the int data are used to differentiate between different layout patterns, and the next 30 bits hold the size data.
So how do we extract the measurement mode and size from the int data? Don't worry, you're going to have to write one at a time. Shift << and Fetch and & operation, Android built-in class Measurespec help us write, we just need to follow the following method can be obtained:

int widthmode = Measurespec.getmode (widthmeasurespec); int widthsize = Measurespec.getsize (Widthmeasurespec);
We have 3 options when setting the width height: wrap_content, match_parent, and specifying a fixed size.
There are also 3 modes of measurement:UNSPECIFIED,exactly,At_most, which are described in more detail in the following three modes.
UNSPECIFIED: The parent container does not have any restrictions on the current view, the current view can take any size
exactly: Current size is the size that the current view should take
at_most: Current size is the maximum size available for the current view

Example:
If we want to customize a view, and the length of a square is 100:

<span style= "FONT-SIZE:18PX;"        >private int getmysize (int defaultsize, int measurespec) {int mysize = defaultsize;        int mode = Measurespec.getmode (MEASURESPEC);        int size = Measurespec.getsize (MEASURESPEC);                Switch (mode) {case measurespec.unspecified: {//If the size is not specified, it is set to the default size mysize = DefaultSize;            Break } case Measurespec.at_most: {//If the measurement mode is the maximum value for size//We will take the maximum value, you can also take other values mysize = Siz                E            Break                } case measurespec.exactly: {//If it is a fixed size, do not change it mysize = size;            Break }} return mysize;} @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec,        HEIGHTMEASURESPEC);        int width = getmysize (+, widthmeasurespec);        int height = getmysize (+, heightmeasurespec); if (width < height) {height= width;        } else {width = height; } setmeasureddimension (width, height);} </span>

<span style= "FONT-SIZE:18PX;" ><com.ljw.myview        android:layout_width= "match_parent"        android:layout_height= "100DP"        android: Background= "#ff0000"/></span>
if we don't rewrite onmeasure then he's going to be wide spread full screen height of 100dp, but we rewrote Onmeasure, and set its width to 100DP, so you don't center set Android:layout_ Width= "Match_parent" is useless.


Rewrite OnDraw ()
Look at the method name to know, is the shape of the drawing view. We can draw directly on the artboard canvas object.
Example:
Suppose we need a circular view, combined with the Onmeasure method we've rewritten above to set the width to the same size.

<span style= "FONT-SIZE:18PX;" > @Overrideprotected void OnDraw (canvas canvas) {//Call the OnDraw function of the parent view because the view class enables us to implement some//basic drawing functions, such as drawing the background color, Background images such as Super.ondraw (canvas), int r = getmeasuredwidth ()/2;//can also be getmeasuredheight ()/2, in this case we have set the width height equal// The horizontal axis of the center is the current view's left start position + radius int centerx = getLeft () + r;//Center's ordinate is the top starting position of the current view + radius int centery = GETTOP () + R; Paint paint = new paint ();p aint.setcolor (Color.green); Start Drawing canvas.drawcircle (CenterX, CenterY, R, paint);} </span>
Summary: The above two methods can achieve custom size, custom shape of view, of course, our real needs are not only these, we also need to add custom attributes such as (Android:layout_width) in the layout file.

Customizing the View's Properties attr

You first need to declare a custom property, declare it in the res/values/styles.xml file (you can create a new one without the file):

<span style= "FONT-SIZE:18PX;" ><resources>    <!--name is a declared "attribute collection" name that can be arbitrarily taken, but preferably set to the same name as our view--    <declare-styleable Name= "MyView" >        <!--Declare our properties, name Default_size, type of dimension (DP,PX, etc.)--        <attr name= "Default_size" format= "Dimension"/>    </declare-styleable></resources></span>
property is defined so that we can directly use it in the layout:
<span style= "FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android "    xmlns:jw=" Http://schemas.android.com/apk/res-auto "    android:layout_width=" Match_parent "    android:layout_height= "Match_parent" >    <com.ljw.myview        android:layout_width= "Match_parent"        android:layout_height= "100DP"        jw:default_size= "100DP"/></linearlayout></span>
Note: You need to set the namespace in the root tag (linearlayout), the namespace name can be arbitrarily taken, such as "JW", the value after the namespace is fixed: "Http://schemas.android.com/apk/res-auto"
In the custom MyView constructor, use the AttributeSet property to take out the custom attributes in the layout:

private int Defalutsize;public MyView (context context, AttributeSet Attrs) {      Super (context, attrs);      The second parameter is the <declare-styleable> tag in the Styles.xml file, the label for the property collection, and the name R.styleable+name TypedArray TARR in the R file      = Context.obtainstyledattributes (Attrs, r.styleable.myview);      The first parameter is the property in the property collection, R file name: R.styleable+ Property Collection name + Underscore + property name      //second parameter is default value      defalutsize = tarr.getdimensionpixelsize (r.styleable.myview_default_size, +);      Finally, remember to release the Typedarray object for recycling      a.recycle ();}
Summary: Comprehensive custom view three-point features (overriding Onmeasure (), OnDraw (), custom layout properties) are basically customizable view!
The following is the complete code for MyView:

/** * @Arthur jovial * 2016-06-15 */public class MyView extends View {private int defalutsize;    Public MyView (Context context) {super (context);        } public MyView (context context, AttributeSet Attrs) {Super (context, attrs); The second parameter is the <declare-styleable> tag in the Styles.xml file, which is the label for the attribute collection, with the name r.styleable+name TypedArray a = Context.obt in the R file.        Ainstyledattributes (Attrs, R.styleable.myview); The first parameter is the property in the property collection, R file name: R.styleable+ Property Collection name + Underscore + property name//The second parameter is the default value Defalutsize = A.getdimensionpixelsize (r.styl Eable.        Myview_default_size, 100);    Release the Typedarray object to the recycle a.recycle ();        } private int Getmysize (int defaultsize, int measurespec) {int mysize = defaultsize;        int mode = Measurespec.getmode (MEASURESPEC);        int size = Measurespec.getsize (MEASURESPEC);                Switch (mode) {case measurespec.unspecified: {//If the size is not specified, it is set to the default size mysize = DefaultSize;            Break       }     Case Measurespec.at_most: {//If the measurement mode is the maximum value for size//We will take the maximum size, you can also take other values mysize = size;            Break                } case measurespec.exactly: {//If it is a fixed size, do not change it mysize = size;            Break    }} return mysize; } @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (widthmeas        Urespec, Heightmeasurespec);        int width = getmysize (defalutsize, Widthmeasurespec);        int height = getmysize (defalutsize, Heightmeasurespec);        if (width < height) {height = width;        } else {width = height;    } setmeasureddimension (width, height); } @Override protected void OnDraw (canvas canvas) {super.ondraw (canvas);//Call the parent class's OnDraw function, the parent class has helped us implement some such as drawing the background color,        Background image, etc.//can also be getmeasuredheight ()/2, in this case we have set the width height equal to int r = Getmeasuredwidth ()/2; The horizontal axis of the center is the left start position of the current view + radius int cenTerx = GetLeft () + R;        The ordinate of the center point is the top start position of the current view + radius int centery = GETTOP () + R;        Paint paint = new paint ();        Paint.setcolor (Color.green);    Start Drawing canvas.drawcircle (CenterX, CenterY, R, Paint); }}

Summary: The custom view is here, I believe you have some understanding. In fact, not complicated, after reading this article I believe you can not wait to try to draw some of their own view!


Custom view See, Next we'll explain the custom viewgroup!

On Android Custom View

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.