Android View Control Architecture analysis View, viewgroup_android

Source: Internet
Author: User
Tags getcolor xml attribute

In Android, view controls are roughly divided into two categories, the ViewGroup and View,viewgroup controls as the parent control, containing and managing the child view, and forming the control tree through ViewGroup and view. Individual Viewgoup objects and view objects are nodes in the control tree. In the control tree, you traverse the search for the corresponding control element in the depth of the tree, while the upper control is responsible for measuring and drawing the child controls and passing the interaction events.

Android Control tree:


Androidui Interface Architecture diagram:


I. Tools for measuring view: measurespec

1.MeasureSpec contains the measurement mode and measurement size, obtains the measurement mode through the Measurespec.getmode (), obtains the measure size through the measurespec.getsize ();

2.MeasureSpec is a 32-bit int value, high 2-bit for measuring mode, low 30-bit for measured size, the purpose of using bit operations is to improve optimization efficiency.

Two. Mode of measurement

1.EXACTLY, exact value mode : Specifies the layout_width or Layout_height attribute as a specific value or match_parent.

2.at_most, Maximum mode : Layout_width or Layout_height specified as wrap_content.

3.UNSPECIFIED: View how big it is

three. The default Onmeasure () method for the view class supports only the exactly mode , and if you want to support other schemas, you must override Onmeasure (), overriding the template code for Onmeasure ():

Package com.example.demoapp.views;
Import Android.content.Context;

Import Android.view.View;
  public class Measuredview extends View {public Measuredview (context) {super (context); @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {//Invoke the Onmeasure () Sup of the parent class
    Er.onmeasure (Measurewidth (Widthmeasurespec), Measureheight (Heightmeasurespec)); or call the Setmeasureddimension () of the parent class directly, because the Onmeasure () of the parent class eventually invokes Setmeasureddimension ()//Setmeasureddimension (
  Measurewidth (Widthmeasurespec), Measureheight (Heightmeasurespec)); /** * Measuring View's width * @param measurespec measurespec Object * @return View's width/private int Measurewidt
    H (int measurespec) {int result = 0;
    int specmode = Measurespec.getmode (Measurespec);
    int specsize = measurespec.getsize (Measurespec);
    if (Specmode = = measurespec.exactly) {result = Specsize;
      else {result = 200; if (Specmode = = measurespec.at_most){result = Math.min (result, specsize);
  } return result; /** * Measure the height of the view * @param measurespec Measurespec Object * @return View's height/private int Measurehe
    ight (int measurespec) {int result = 0;
    int specmode = Measurespec.getmode (Measurespec);
    int specsize = measurespec.getsize (Measurespec);
    if (Specmode = = measurespec.exactly) {result = Specsize;
      else {result = 200;
      if (Specmode = = measurespec.at_most) {result = Math.min (result, specsize);
  } return result;


Four. The drawing of view

1.2D Drawing Essential Tool--canvas

1 The way to get the canvas object:

A. Passing in a parameter from a method, for example, a parameter in the view's OnDraw () is a canvas object

B. Constructed by means of a construction method, namely: Canvas Canvas = new Canvas (bitmap), a Canvas object can be obtained by passing a bitmap object in the constructor of the Canvas. The process of constructing a Canvas object by passing in a bitmap object is called a "canvas mount," and the incoming bitmap object hosts a number of pixel information drawn on the Canvas, invoking the Canvas.drawxxx method (such as: Canvas.drawbitmap ( Bitmap, 0, 0, NULL) will all occur on the bitmap object.

2) using canvas drawing

A. Drawing through the canvas.drwaxxx will directly affect the bitmap object, and when we refresh the view again, we will be drawn to the bitmap object that has changed;

B. Drawing using canvas and paint;

C. No matter how complex, exquisite space, can be divided into small graphic units, we only find these graphic units, you can draw the control.

Five. Measurement of ViewGroup

The role of 1.ViewGroup: Management of Child view, such as the size of the child view, location;

2.ViewGroup by traversing the child view, call the measure () of the child view to obtain the measurement results of each child view;

3.ViewGroup after the child view is measured, call the layout () of the child view to place the child view in the appropriate position;

4. When customizing ViewGroup, the display of onlayout () control child view is usually overridden;

5. If you need to support the Wrap_content property, you must override Onmeasure ().

Vi. Drawing of ViewGroup

Typically, Viewgoup does not need to be drawn, but ViewGroup uses Dispatchdraw () to draw its child view.

Seven. Customize view

1. When customizing view, it is often necessary to rewrite OnDraw () to draw the view to display, if you also need to support wrap_content properties, you must rewrite onmeasure ();

2. The new view property can be set by customizing the Attrs property;

Some important callback methods in 3.View:

1) onfinishinflate (): Loading the build callback from the XML;

2) onsizechanged (): Callback when component size changes;

3) Onmeasure (): for measurement;

4) OnLayout (): Set the display position;

5) Ontouchevent (): Touch event.

4. Three common ways to implement custom view:

1) to extend the native control by rewriting the OnDraw ();

2 implement new controls by combining them, usually integrating a suitable amount of viewgoup, and then adding a control with the specified functionality through AddView () to group the new composite control.

3 Rewrite view to implement a completely new control, by overriding OnDraw (), Onmeasure () Implementing drawing Logic, overriding ontouchevent () to implement interactive logic.

5. Custom Properties

1 Custom attributes: In the RES resource directory, create a attrs.xml attribute definition file in the values directory, file Template:

<?xml version= "1.0" encoding= "Utf-8"?>
  <declare-styleable name= "Customattr" >
    <attr name= "title" format= "string"/>
    <attr name= "FontSize" format= "Dimension"/>
    < attr name= "fontcolor" format= "color"/> <attr name=
    "Background" format= "Reference|color"/>
    < attr name= the "FontStyle" format= "enum"/> <attr name= "Shadesupport"
    format= "boolean"
  /> Declare-styleable>

2 Get the custom attribute set through TypedArray, get the property value by Typedarray.getstring (), Typedarray.getcolor (), and the template code:

Package com.jy.myrecyclerview.test;
Import Android.content.Context;
Import Android.content.res.TypedArray;
Import Android.util.AttributeSet;

Import Android.view.View;

 /** * Created by 123 on 2016/5/6.
  * * public class Testcustomattrs extends View {private context mcontext;
  Private AttributeSet Mattrs;
  Private String Mtitle;
  private float mfontsize;
  private int mfontcolor;
  private int mbackground;
  private int mfontstyle;

  Private Boolean Mshadesupport;
    Public Testcustomattrs {Super (context);
  This.mcontext = context;
    Public Testcustomattrs (context, AttributeSet attrs) {Super (context, attrs);
    This.mcontext = context;
  This.mattrs = Attrs; Testcustomattrs (context, AttributeSet attrs, int defstyleattr) {Super (context, Attrs, Defstyleatt
    This.mcontext = context;
  This.mattrs = Attrs; } private void Getcustomattrs () {TypedArray ta = mconteXt.obtainstyledattributes (Mattrs, r.styleable.customattr);
    Mtitle = ta.getstring (R.styleable.customattr_title);
    Mfontsize = Ta.getdimension (r.styleable.customattr_fontsize, 10);
    Mfontcolor = Ta.getcolor (r.styleable.customattr_fontcolor, 0);
    Mbackground = Ta.getcolor (r.styleable.customattr_background, 0);
    Mfontstyle = Ta.getint (r.styleable.customattr_fontstyle, 0);
    Mshadesupport = Ta.getboolean (R.styleable.customattr_shadesupport, false);
  Ta.recycle ();

6. Define callback interface to realize flexible control of custom control;

7. Referencing a UI template

1 custom controls need to be introduced using namespaces: xmlns:custom= "Http://", the name of the custom control will be named Custom

2 When using custom attributes in an XML file, you can use this namespace to refer to the following code template:

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android=
"" /res/android "
  xmlns:custom=" Http:// "
  android:layout_width=" Match_ Parent "
  android:layout_height=" match_parent ">

    Android:id= "@+id/id_recyclerview"
    android:divider= "#ffff0000"
    android:dividerheight= "10DP"
    Android : layout_width= "match_parent"
    android:layout_height= "match_parent"
    custom:title= "title"
    Custom: Fontsize= "12SP"
    custom:fontcolor= "@color/colorprimary"
    custom:background= "@color/colorprimary"
    Custom:shadesupport= "false"/>


Nine. Custom ViewGroup

1. Methods to be rewritten:

1) onmeasure (): The pair view is measured;

2) OnLayout (): Set the position of the child view;

3) Ontouchevent (): Set touch interaction events.

The above is the entire content of this article, I hope to help you learn.

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: 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.