The drawing process of view in Android Onmeasure method brief with custom view example

Source: Internet
Author: User
Tags getcolor

The drawing process of view in Android

When the activity receives the focus, it will be asked to draw its own layout, and the Android framework will handle the drawing process, and the activity simply provides the root node of its layout.

The drawing process starts at the root node of the layout and measures and plots the entire layout tree from the root node.

Each of the viewgroup is responsible for asking every child of it to be drawn, and each View is responsible for drawing itself.

Because the entire tree is traversed sequentially, the parent node is drawn first, and the sibling nodes are drawn in the order in which they appear in the tree.

  

  Drawing is a two-pass process: A measure pass and a layout pass.

  The measurement process (measuring pass) is implemented in measure (int, int) , from top to bottom of the tree.

In this recursive process, each view will pass on its own dimension specifications.

At the end of the measure pass, each view stores its own measurements, the measurement result.

The second is the layout pass, which occurs in layout (int, int , int, int) and still from top to bottom (Top-down).

In this time, each parent will be responsible for the size of the measurement process, and put all of their children in the right place.

Dimension Parent-child relationship processing

When the measure () method of a View object returns, its getMeasuredWidth() and getMeasuredHeight() values should be set, and the values of all its descendants should be set together as well.

 The value of the measured width and measured height of a view object must take into account the restrictions that its parent container gives it.

This ensures that at the end of the measure pass, all the parent accepts the measurements result of all of its children.

  Note: A parent may call the measure () method more than once to its child.

For example, the first time a parent might measure every child of it, and did not specify the size, the parent just to find out how much they want;

If, after the first pass, the unlimited size sum of all the children is too large or too small, the parent will again call the measure () method on its child, when the parent will set the rules, intervene in the process, and use the actual values.

(That is, to allow children to develop freely, so parents intervene ).

Layout Property Description

  layoutparams is a parameter that the view uses to tell its parent container how it wants to be placed.

The most basic Layoutparams base class simply describes how large the view wants to be, indicating the size attribute.

That is, when the view is in the XML layout, it usually needs to specify the width and Height properties.

  Each dimension can be specified as one of the following three values:

1.fill_parent (renamed to match_parentafter API level 8) indicates that the view wants to be as large as its PARENT (minus the margins).

2.wrap_content, which means that the view wants to be just as large as it can contain (including margins).

3. specific values .

Different subclasses of ViewGroup (different layout classes) have corresponding Layoutparams subclasses, which contain more layout-related properties.

Onmeasure Method

  The onmeasure method is to measure the view and its contents, to determine measured width and measured height, and This method is evoked by the measure(int, int) method, Subclasses can overwrite onmeasure to provide more accurate and efficient measurements.

There is a convention: when covering the Onmeasure method, it must be called setMeasuredDimension(int,int) to store the view's measured measured width and height.

If this is not done, a illegalstateexceptionwill be thrown by the measure (int, int) method.

The declaration of the Onmeasure method is as follows:

protected void onmeasure (int widthmeasurespec, int heightmeasurespec)

Two of these input parameters:

Widthmeasurespec

Heightmeasurespec

The horizontal and vertical space requirements proposed by the parent are respectively.

These two requirements are coded according to the View.measurespec class.

See View.measurespec for a description of this class: This class wraps the layout request passed down from the parent and passes it to the child.

Each of the MEASURESPEC represents a requirement for width or height.

  Each of the MEASURESPEC has a size (size) and a pattern (mode).

Measurespecs This class provides a way to wrap a <size, mode> tuple into an int type, thus reducing the allocation of objects. Of course, the inverse parsing method is provided, and the size and mode are solved from the int value.

  There are three types of modes:

  UNSPECIFIED

This means that the parent does not impose any restrictions on child, and the child can be any size it wants.

  Exactly

The parent determines an absolute size for child, and child will be given these boundaries, regardless of how much she wants.

  At_most

The child can be of any size, but has an absolute size limit.

When covering the Onmeasure method, the subclass is responsible for ensuring that the measured height and width are at least the minimum height and width of the view.

(and). getSuggestedMinimumHeight() getSuggestedMinimumWidth()

OnLayout

This method is called in the layout pass to determine the placement and size of the view. Method declaration:

protected void OnLayout (Boolean changed, int left, int top, int. right, int bottom)

The upper and lower left and right parameters are relative to the parent.

If the view contains a child, then each child needs to be laid out in onlayout.

Custom View Demo

The Labelview class in API demos is an example of a custom class that inherits from view:

/* Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License") ; * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.example.android.apis.view;//need the following import to get access to the app resources, since this//Clas S is in a sub-package.import android.content.context;import android.content.res.typedarray;import Android.graphics.canvas;import Android.graphics.paint;import Android.util.attributeset;import Android.view.View; Import com.example.android.apis.r;/** * Example of how to write a Custom subclass of View. LabelView * is used-draw simple text views. Note that it does not handle * styled text or right-to-left writing systems.    * */public class LabelView extends View {private Paint mtextpaint;    Private String MText;        private int mascent;  /** * Constructor.     This version was only needed if you'll be instantiating * The object manually (not from a layout XML file).        * @param context */public LabelView (context context) {super (context);    Initlabelview (); }/** * Construct object, initializing with any attributes we understand from a * layout file.     These attributes is defined in * sdk/assets/res/any/classes.xml. * * @see Android.view.view#view (android.content.Context, Android.util.AttributeSet) */Public LabelView (Contex        T context, AttributeSet Attrs) {Super (context, attrs);        Initlabelview (); TypedArray a = Context.obtainstyledattributes (Attrs, R.styLeable.        LabelView);        Charsequence s = a.getstring (R.styleable.labelview_text);        if (s! = null) {SetText (s.tostring ());        }//Retrieve the color (s) to is used for this view and apply them. Note, if you are supporting a single color, so you//can instead call A.getcolor () and pass that        To SetTextColor ().        SetTextColor (A.getcolor (R.styleable.labelview_textcolor, 0xff000000));        int textSize = A.getdimensionpixeloffset (r.styleable.labelview_textsize, 0);        if (TextSize > 0) {settextsize (textSize);    } a.recycle ();        Private final void Initlabelview () {mtextpaint = new Paint ();        Mtextpaint.setantialias (TRUE); Must manually scale the desired text size to match screen density mtextpaint.settextsize (* getresources (). Get        Displaymetrics (). density);        Mtextpaint.setcolor (0xff000000);    Setpadding (3, 3, 3, 3); }/** * Sets the TexT to display in this label * @param text of the text to display.     This is drawn as one line.        */public void SetText (String text) {mText = text;        Requestlayout ();    Invalidate ();         }/** * Sets the text size for this label * @param size Font size */public void settextsize (int size) {        This text size have been pre-scaled by the Getdimensionpixeloffset method mtextpaint.settextsize (size);        Requestlayout ();    Invalidate ();     }/** * Sets the text color for this label.        * @param color ARGB value for the text */public void SetTextColor (int color) {mtextpaint.setcolor (color);    Invalidate (); }/** * @see android.view.view#measure (int, int) */@Override protected void onmeasure (int widthmeasuresp EC, int heightmeasurespec) {setmeasureddimension (Measurewidth (Widthmeasurespec), Measureheight (Heig    HTMEASURESPEC)); }/** * Determines the WIDTH of this view * @param measurespec A Measurespec Packed to an int * @return The width of the view, honoring C        Onstraints from Measurespec */private int measurewidth (int measurespec) {int result = 0;        int specmode = Measurespec.getmode (Measurespec);        int specsize = measurespec.getsize (Measurespec);        if (Specmode = = measurespec.exactly) {//We were told how big to be result = specsize;                    } else {//Measure the text result = (int) mtextpaint.measuretext (mText) + getpaddingleft ()            + Getpaddingright (); if (Specmode = = Measurespec.at_most) {//Respect At_most value if that was ' what's ' called for by Measuresp            EC result = Math.min (result, specsize);    }} return result; }/** * Determines the height of this view * @param measurespec A Measurespec Packed to an int * @return The height of the view, Honoring constraints from Measurespec */private int measureheight (int measurespec) {int result = 0;        int specmode = Measurespec.getmode (Measurespec);        int specsize = measurespec.getsize (Measurespec);        mascent = (int) mtextpaint.ascent ();        if (Specmode = = measurespec.exactly) {//We were told how big to be result = specsize; } else {//Measure the text (beware:ascent is a negative number) result = (int) (-mascent + MTEXTP            Aint.descent ()) + getpaddingtop () + Getpaddingbottom (); if (Specmode = = Measurespec.at_most) {//Respect At_most value if that was ' what's ' called for by Measuresp            EC result = Math.min (result, specsize);    }} return result;    /** * Render The text * * @see Android.view.view#ondraw (android.graphics.Canvas) */@Override protected void OnDraw (canvas canvas) {Super. OnDraw (canvas);    Canvas.drawtext (MText, Getpaddingleft (), Getpaddingtop ()-mascent, Mtextpaint); }}

The drawing process of view in Android Onmeasure method brief with custom view example

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.