An analysis of the custom view of "Android-Advanced"

Source: Internet
Author: User
Tags dashed line

1 overview

Android Custom View/viewgroup the steps are outlined below:

1)  custom attributes, 2)  Selecting and setting the construction method, 3)  overriding the Onmeasure () method, 4)  overriding the OnDraw () method; 5)  overriding the OnLayout () method; 6)  Methods to rewrite other events (swipe to listen, etc.).

2 Custom Properties

Android custom properties are defined, used, and obtained in three steps.

2.1 Defining custom Properties

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

We typically define custom properties in the/values/attr.xml file (the Attr.xml file needs to be created yourself).

Let's take a look at the sample code:

<?XML version= "1.0" encoding= "Utf-8"?><Resources>    <attrname= "Rightpadding"format= "Dimension" />    <declare-styleablename= "Custommenu">        <attrname= "Rightpadding" />    </declare-styleable></Resources>

As you can see, we first define a property rightpadding, and then we refer to this property in Custommenu. Here's a description:

    • First, we can define attributes directly in the declare-stylable tag without referencing externally defined properties, but for the reuse of attributes, we can choose the above method: define first, then reference;
    • Declare-stylable tags are only intended to classify custom attributes. There may be more than one custom control in a project, but only one attr.xml file, so we need to categorize the custom attributes in different custom controls, which is why the name attribute in the declare-stylable tag is often defined as a custom control;
    • The so-called reference in the declare-stylable tag is to remove the external definition of the Format property, if it does not remove format, it will be an error, if the external definition does not have format in the internal reference and format, will also be an error.

Common format types:

1) String  : String type, 2)  integer: Integer type, 3)  float: float, 4)  dimension: size, rear must be with DP, dip, PX, SP and other units; 5)  Boolean: 6)  Reference: Reference type, passing in the ID of a resource, must begin with the "@" symbol, 7) color  : color, must be "#" symbol beginning, 8)  fraction: percent, must be "% "End of symbol; 9)  enum: enum type

Here are a few things to note about the format type:

    • Multiple types can be written in format, with "|" in the middle The symbol is split open, indicating that these types can pass this attribute;
    • An example of a definition of an enum type is shown in the following code:
<Resources>    <attrname= "Orientation">        <enumname= "Horizontal"value= "0" />        <enumname= "vertical"value= "1" />    </attr>    <declare-styleablename= "CustomView">        <attrname= "Orientation" />    </declare-styleable></Resources>

Make use of the Getint () method to obtain the value and determine, depending on the value of different operations can be.

2.2 Using Custom Attributes

When using custom attributes in an XML layout file, we need to define a namespace first. Android's default namespace is Android, so we can usually use the "android:xxx" format to set a property of a control, Android this namespace definition is defined in the header tag of the XML file, This is usually the case:

Xmlns:android= "Http://schemas.android.com/apk/res/android"

Our custom properties are not in this namespace, so we need to add a namespace.

The namespace of the custom attribute is as follows:

xmlns:app= "Http://schemas.android.com/apk/res-auto"

As you can see, in addition to changing the name of the namespace from Android to app, the last "Res/android" is changed to "Res-auto".

Note: The name of the custom namespace can be defined by itself, not necessarily the app.

2.3 Getting custom properties

In the custom view/viewgroup, we can get the custom properties through Typedarray. The sample code is as follows:

 PublicCustommenu (context context, AttributeSet attrs,intdefstyleattr) {    Super(context, attrs, defstyleattr); TypedArray a= Context.gettheme (). Obtainstyledattributes (Attrs, R.styleable.custommenu, defstyleattr, 0); intIndexcount =A.getindexcount ();  for(inti = 0; i < Indexcount; i++) {        intattr =A.getindex (i); Switch(attr) { Caser.styleable.custommenu_rightpadding:mmenurightpadding= A.getdimensionpixelsize (attr, 0);  Break; }} a.recycle ();}

Here's what you need to explain:

    • The code that gets the custom property is usually written in the construction method of three parameters (specifically why three parameters are constructed, as explained in the following sections);
    • The custom property set (Custommenu) for which the custom view is bound when the Typedarray object is obtained, the number of custom properties is obtained through the GetIndexCount () method, and a property is obtained through the GetIndex () method. Finally, the property is judged by the switch statement and the corresponding operation is performed.
    • After the Typedarray is used, the recycle () method needs to be called to reclaim it.

3 Construction methods

When we define a new class that inherits the view or ViewGroup, the system prompts us to rewrite its construction method. View/viewgroup four more construction methods can be overridden, each with one or two, three or four parameters. The four-parameter construction method we usually do not use, so in this chapter we mainly introduce a parameter, two parameters and three parameters of the construction method (here is the Custommenu control as an example).

3.1 How to construct a parameter
Code to construct the method: public   custommenu (context context) {...}

This constructor method has only one parameter context context. This method is called when we create the control directly in Java code through the new key.

3.2 Construction methods of two parameters
Code to construct the method: public   custommenu (context context, AttributeSet Attrs) {...}

This construction method has two parameters: Context contexts and AttributeSet property sets. This constructor is called by default when we need to get the property in a custom control. The AttributeSet object is all the properties defined in this control.

We can get the number of attributes through the Getattributecount () method of the AttributeSet object, get the name of an attribute through the Getattributename () method, and pass the Getattributevalue () Method gets the value of a property.

Note: This constructor is called by default, regardless of whether a custom attribute is used, and it is wrong to say that the constructor of three parameters is invoked by default using a custom property.

3.3 Construction methods of three parameters
Code for Constructing method: public  int defstyleattr) {...}

There are three parameters in this constructor: A context context, a AttributeSet property set, and a reference to a Defstyleattr custom property. This constructor method is not called by default and must be called manually, the only difference between this constructor and the two-parameter constructor is that this constructor gives us a default set of properties passed in.

Defstyleattr points to the custom attribute set defined in the <declare-styleable> tag of the custom attribute, and we need to use defstyleattr when creating the Typedarray object.

3.4 Integration of three construction methods

In general, we will concatenate these three construction methods, that is, layer calls, so that the final business process is focused on three parameters of the construction method. We let the constructor of one parameter refer to the construction method of two parameters, and the construction method of the two parameters refers to the construction method of the three parameters. The sample code is as follows:

 Public Custommenu (Context context) {    thisnull);}  Public Custommenu (Context context, AttributeSet attrs) {    This (context, attrs, 0);}   Public int defstyleattr) {    Super(context, attrs, defstyleattr);     // Business code }

In this way, you can guarantee that the control will be created regardless of how it was used, and eventually it would be processed in three parameter construction methods, reducing duplication of code.

4 Onmeasure ()

The Onmeasure () method is primarily responsible for measuring the width and height of the control itself or its child controls. We can obtain the measurement mode and the measured value (measurement = measurement mode + measured value) of the width and height of the control separately by the parameters Widthmeasurespec and Heightmeasurespec provided by the Onmeasure () method.

Widthmeasurespec and Heightmeasurespec are only values of type int, but they are encoded by the Measurespec class, which encapsulates the measurement mode and the measured value, So we can pass Measurespec.getmode (XMEASURESPEC) and Measurespec respectively. GetSize (XMEASURESPEC) to obtain the measurement mode and measurement values of the control or its child view.

The measurement mode is divided into the following three cases:

1)  exactly: when the width and height value is set to a specific value, such as 100DIP, Match_parent, and so on, the size taken out at this time is accurate size; 2)  at_most: Used when the width and height values are set to Wrap_content The size taken out at this time is the maximum available space for the control, and 3)  UNSPECIFIED: Used when there is no specified width and height value (rarely seen).

Methods commonly used in the Onmeasure () method:

1)  Getchildcount (): Gets the number of child view; 2)  Getchildat (i): Gets the sub-control of I, 3)  subview.getlayoutparams (). width/ Height: Sets or gets the width or height of the child controls; 4)  measurechild (Child, Widthmeasurespec, Heightmeasurespec): Measure the height of the sub-view; 5)  Child.getmeasuredheight/width (): After executing the Measurechild () method, you can obtain the width and height of the child view in this way; 6)  getpaddingleft/right/top/ Bottom (): Gets the four-week padding of the control, 7)  setmeasureddimension (width, height): Sets the width height of the control. If you write this code, you need to delete "super." Onmeasure (Widthmeasurespec, heightmeasurespec); " This line of code.

Note:the Onmeasure () method may be called more than once because the content or child view in the control may be "dissatisfied" with the space assigned to it, and therefore requests the space to be reassigned to the parent space.

5 OnDraw ()

The OnDraw () method is responsible for drawing, that is, if the effects we want to get are not readily available in Android native controls, then we need to draw our own custom controls to display them.

To learn the OnDraw () method, we need to learn the top two classes used in the OnDraw () method: Paint and canvas.

Note: the OnDraw () method is triggered each time the custom View/viewgroup is touched.

5.1 Paint Class

Paint Brush object, which contains style and color information for drawing geometry, text, and bitmaps, specifying how to draw text and graphics. There are many ways to set up the Brush object, which can be divided into two categories: one is related to drawing, the other is related to text drawing.

Paint The following methods are available in the class:

1. Graphic Drawing:

1)  Setargb (int A, int r, int g, int b): Sets the color of the drawing, a for transparency, R, G, b for color values, 2)  setalpha (int a): Sets the transparency of the plotted drawing; 3)  SetColor (int color): Sets the color of the drawing, 4)  Setantialias (Boolean a): Sets whether anti-aliasing is used, anti-aliasing consumes a large resource, and the drawing speed slows down; 5)  Setdither ( Boolean B): Set whether to use Image jitter processing, will make the image color more smooth and full, clearer; 6)  Setfileterbitmap (Boolean B): Set whether to filter out the bitmap optimization in the animation, can speed up the display speed; 7)  Setmaskfilter (maskfilter MF): Set the Maskfilter to achieve the effect of the filter; 8)  Setcolorfilter (Colorfilter CF): Set the color filter, can be used to achieve different color conversion effect when drawing colors; 9)  setpatheffect (patheffect PE): Set the effect of the drawn path; 10) Setshader (Shader s): Set Shader to draw various gradient effects; Setshadowlayer (float R, int x, int y, int c): Set the shadow layer under the graph, R is the shadow angle, X and y are the distance of the shadow on the X and Y axes, and C is the color of the shadow; SetStyle (Paint.style s): Sets the style of the brush: FILL solid, stroke Hollow, fill_or_stroke at the same time solid and hollow; 13) Setstrokecap (Paint.cap C): Sets the brush's graphic style when the stroke or fill_or_stroke is set, and the Setstrokejoin (Paint.join j): Sets how the shapes are combined when drawing ) Setstrokewidth (float W): Sets the brush's thickness when the brush style is stroke or fill_or_stroke, and Setxfermode (Xfermode m): Sets the processing mode when the graphics overlap;

2. Text rendering:

1)  settextalign (Path.align a): Sets the alignment of the drawn text, 2)  Settextscalex (float s): Sets the scale of the text in the x-axis, can achieve the text stretching effect; 3)  Settextsize (float s): Set font size, 4)  settextskewx (float s): Set italic text, S is Text tilt, 5)  settypeface (TypeFace tf): Set font style, including bold , italic, etc; 6)  Setunderlinetext (Boolean B): Sets whether the drawn text is underlined, 7)  Setstrikethrutext (Boolean B): Sets whether the drawn text has a strikethrough effect; 8)  Setfakeboldtext (Boolean B): Simulate the implementation of bold text, if set in small font effect will be very poor; 9)  Setsubpixeltext (Boolean B): If set to True will help the text to display the effect on the LCD screen;

3. Other methods:

1)  gettextbounds (String t, int s, int e, Rect b): The area of the page in which the T-text starts from the S subscript to the end of the e-subscript is enclosed in a rectangle of B; 2)  Clearshadowlayer (): Clear the Shadow layer, 3)  Measuretext (String t, int s, int e): Returns the width of all characters in the T text from the start of the S subscript to the end of the e subscript; 4)  Reset () : Resets the brush to the default value.

Here are a few ways to explain:

1. Setpatheffect (patheffect PE): Sets the effect of the drawn path:

Some of the following options are commonly available:

1)  Cornerpatheffect: can use fillet to replace sharp angle, 2)  Dathpatheffect: Dashed line, consist of short line and dot; 3)  Discretepatheffect: thorn-like lines; 4)  Pathdashpatheffect: Defines a new shape and marks it as the outline of the original path; 5)  Sumpatheffect: The effect of adding parameters in a path in order; 6)  Composepatheffect: Combine the two effects, using the first effect, based on which the second effect is applied.

2, Setxfermode (xfermode m): Sets the processing mode when graphics overlap:

For the various effects of xfermode, we can refer to the following picture:

In use, we need to pass the paint. Setxfermode (New Porterduffxfermode (PorterDuff.Mode.XXX)) to set, XXX is a constant parameter that corresponds to one of the modes, such as Dst_out.

5.2 Canvas Class

Canvas is the canvas on which you can draw many things using the paint brush object.

Canvas objects can be drawn in:

1)  DrawArc (): Draw arc, 2)  Drawbitmap (): Draw bitmap Image, 3)  drawcircle (): Draw Circle, 4)  drawLine (): Draw line; 5)  DrawOval (): Draw ellipse, 6)  DrawPath (): Draw path, 7)  drawpicture (): Draw picture image; 8)  DrawRect (): Draw rectangle; 9)  Drawroundrect (): Draw rounded rectangles; DrawText (): Draw text; DrawVertices (): Draw vertices.

Canvas other methods of the object:

1)  Canvas.save (): Save the currently drawn image so that subsequent operations are plotted on a new layer, 2)  Canvas.restore (): Adjusts the current canvas to the previous save () state; 3)  canvas.translate (dx, dy): Move the origin of the current canvas to the (dx, dy) point, followed by (DX, DY) point as a reference; 4)  Canvas.scale (x, y): scales the current canvas horizontally by x times, scales y times vertically, 5)  canvas.rotate (angle): Rotates the current canvas angle degrees clockwise.

6 OnLayout ()

The OnLayout () method is responsible for layout, most of which is overridden in custom ViewGroup, and is primarily used to determine where sub-view is placed in this layout space.

The OnLayout (boolean changed, int l, int t, int r, int b) method has 5 parameters, where changed indicates whether the control has a new size or position; L, T, R, b indicate the view is relative to the parent layout's left/right/ The position below.

The following are the methods commonly used in the OnLayout () method:

1)  Getchildcount (): Gets the number of child view; 2)  Getchildat (i): Get sub-View3)  getwidth/height (): Get Onmeasure () The measured value of the width and height returned in; 4)  child.getlayoutparams (): Gets the Layoutparams object to the child view; 5)  child.getmeasuredwidth/height () : Gets the width and height values of the sub-view measured in the Onmeasure () method, 6)  Getpaddingleft/right/top/bottom (): Gets the four-week padding for the control, 7)  child.layout (L, T, R , b): Sets the coordinates of the upper and lower left and right sides of the child view layout.

7 Other Methods 7.1 Generatelayoutparams ()

The Generatelayoutparams () method is used in custom ViewGroup to indicate the relationship between child controls, which is the layoutparams corresponding to the current viewgroup. We just need to return an object of the Layoutparams type we want to use in the method.

In the Generatelayoutparams () method, you need to pass in a AttributeSet object as a parameter, which is the property set of this ViewGroup, and the system defines the layout rules of the child view based on this viewgroup attribute set. For child view use.

For example, in a custom streaming layout, we only need to care about the spacing between the child controls, so we need to return a new Marginlayoutparams () in the Generatelayoutparams () method.

7.2 ontouchevent ()

The Ontouchevent () method is used to monitor the user's finger operation. We get the user's gestures in real time through the Getaction () method of the Motionevent parameter object in the method, with up, down, and move three enumeration values, which represent the actions used to lift, press, and slide the finger. Each time the user has an action, the Ontouchevent () method is returned.

7.3 onscrollchanged ()

If our custom View/viewgroup is an inherited control that can be scrolled, such as Scrollview/horizontalscrollview, you can listen to the control's scrolling events by overriding the Onscrollchanged () method.

There are four parameters in this method: L and T represent the coordinates of the points currently sliding to the horizontal and vertical directions, and the OLDL and Oldt indicate the coordinates of the last slide to the horizontal and vertical directions. We can work with these four values for sliding, such as adding property animations.

7.4 Invalidate ()

The function of the invalidate () method is to request that the view tree be redrawn, the draw () method, and the layout () method is called if the size of the view changes.

usually causes invalidate () the functions of the operation are as follows:

1)  Call the Invalidate () method directly, request a re-draw (), but only draw the caller itself, 2)  call the SetSelection () method, request a redraw (), but only draw the caller itself; 3)  Calling the Setvisibility () method, calling the invalidate () method indirectly, and then drawing the view;4)  calls the SetEnabled () method, requests a redraw (), but does not redraw any views, including the caller itself.

7.5 Postinvalidate ()

Functionality is the same as the invalidate () method, except that the Postinvalidate () method is an asynchronous request to redraw the view.

7.6 Requestlayout ()

The Requestlayout () method simply re-layouts the layout of the view tree (including the measure () procedure and the Layout () procedure) and does not call the draw () procedure, which means that no view is redrawn, including the caller itself.

7.7 Requestfocus ()

The draw () procedure for the view tree is requested, but only the view that needs to be redrawn is drawn, that is, which view or ViewGroup called the method, and which one is redrawn.

8 Summary

Finally, let's take a look at the order of the various functions called when customizing View/viewgroup, as shown in:

In these methods:

Onmeasure () calls one to several times after initialization to measure the width of the control or its child controls;

OnLayout () is called once after the Onmeasure () method to lay out the control or its child controls;

OnDraw () is called once after the OnLayout () method and is called multiple times when the user's finger touches the screen to draw the control.

An analysis of the custom view of "Android-Advanced"

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.