Layout mechanism of Android view frame

Source: Internet
Author: User

Overview

The Android View framework works in three main processes:

1. View tree measurement (measure) measure mechanism of Android view frame

2. Layout of the view tree layoutsmechanism of Android view frame

3. View tree Draw (draw)The draw mechanism of the Android view frame

The workflow for the view frame is to measure each view size (measure) and place each view in the appropriate location (layout) and draw each view (draw).

This paper mainly describes the layout process in the three major processes. If you do not know the measure process, you can refer to the measure mechanism of this article Android view framework.

Think about the entire layout process with questions.

1, why should the system have layout process?

The view frame successfully calculates the dimensions of each view after the first step of the measure process. But to successfully draw the view to the screen, only the size of the view is not available, and you need to know exactly where the view should be drawn. In addition, for a viewgroup, also need to according to their own specific layout rules, to correctly calculate the sub-view of the drawing position, has achieved the correct layout purposes. This is also the responsibility of the layout process.

The position is the relative position of the view relative to the parent layout coordinate system, not the absolute position in the screen coordinate system. This makes it easier to maintain the recursive nature of the tree structure and the internal autonomy. The view position can be infinitely large beyond the current ViewGroup, which is also the principle of sliding effect by changing the view position.

2, the layout process has done something?

Because view is stored as a tree structure, the typical data manipulation is recursive, so the layout process of internal autonomy is adopted in the view frame.

Each leaf node according to the parent node passed the location information, set their own location data, each non-leaf node, in addition to the parent node is responsible for the location information passed over, set their own location data (if there is a parent node), but also according to their own internal layout rules (such as vertical arrangement, etc.), Calculates the location information for each child node, and then passes the layout procedure to the child nodes.

For ViewGroup, in addition to setting your own location based on the location information passed by your parent, you also need to calculate the exact position (relative to the location of the parent layout of the child view) for each child view according to your layout rules.

For view, set your own location based on the location information passed by your parent.

The location information of the view object is stored internally with 4 member variables, namely Mleft, Mright, Mtop, Mbottom. their meaning.

Source Code Analysis

In the view source code, the following information about the layout process is extracted.

We know that the root node of the entire view tree is Decorview, which is a framelayout, so it is a viewgroup, so the whole view tree is measured from the layout method of a ViewGroup object.

View:1, layout

/**

Assigning a location to a view, each parent invokes children's layout method to set the location of the children. It is better not to overwrite this method, there is children ViewGroup, should overwrite OnLayout method

*/

public void layout (int l, int t, int r, int b);

Source:
It is not given here, if you are interested, check the SDK yourself.


Pseudo code:

 Public voidLayoutintLintTintRintb) {if(according to some flags, it is found that further measure is needed) {onmeasure (Moldwidthmeasurespec, Moldheightmeasurespec); } //staging the old location information intOLDL =Mleft; intOldt =Mtop; intOldb =Mbottom; intOldr =Mright; //to set up new location informationMleft =l; Mtop=T; Mbottom=b; Mright=R; if(Layout changed | |layout required)            {onlayout (changed, L, T, R, b); //Callback Layoutchange Event         for(Traverse Listener) {Listener.onlayoutchange ( This, L, T, R, B, Oldl, Oldt, Oldr, OLDB); }} is marked as having performed layout;} 



2, OnLayout


/** the location of each sub-view is calculated according to the layout rules, and the view class defaults to an empty implementation. So there is no source code */
protected void OnLayout (Boolean changed, int left, int top, int. right, int bottom);

ViewGroup:

In ViewGroup, you only need to override the OnLayout method to calculate the location of each sub-view and pass the layout process to the child view.

Source:

ViewGroup is not implemented, the OnLayout method of LinearLayout and relativelayout can be referenced in detail. Although each implementation is complex, the basic process is the same, and you can refer to the pseudocode below.

Pseudo code:

protected void OnLayout (booleanint int int int b) {    for  (Traverse child view) {        /** is         calculated based on the following data.            1, their current layout rules. such as vertical emissions or horizontal emissions.            2, sub-view measurement size.            3. Position of child view in all child view. such as position index, first or second.         */         calculates the location information of each sub-view;                 Child.layout (the position information calculated above);}        }


Conclusion

In general, custom view, if the view does not contain sub-view, similar to TextView, is not required to overwrite the OnLayout method. With sub-view, such as linearlayout, you need to calculate the location of each sub-view according to your own layout rules.

Hands-on Operation

Let's write a custom viewgroup to make each sub-view of it appear vertically, and let the left side of each sub-view be a distance from the left edge of the previous child view, presumably as shown:

The actual operating effect is as follows:

The code is as follows:

 Public classVerticaloffsetlayoutextendsViewGroup {Private Static Final intOFFSET = 100;  PublicVerticaloffsetlayout (Context context) {Super(context); }     PublicVerticaloffsetlayout (Context context, AttributeSet attrs) {Super(context, attrs); }     PublicVerticaloffsetlayout (context context, AttributeSet attrs,intdefstyleattr) {        Super(context, attrs, defstyleattr); } @Overrideprotected voidOnmeasure (intWidthmeasurespec,intHeightmeasurespec) {        Super. Onmeasure (Widthmeasurespec, Heightmeasurespec); intWidthmode =Measurespec.getmode (WIDTHMEASURESPEC); intHeightmode =Measurespec.getmode (HEIGHTMEASURESPEC); intWidthsize =measurespec.getsize (WIDTHMEASURESPEC); intHeightsize =measurespec.getsize (HEIGHTMEASURESPEC); intwidth = 0; intHeight = 0; intChildCount =Getchildcount ();  for(inti = 0; i < ChildCount; i++) {View child=Getchildat (i); Viewgroup.layoutparams LP=Child.getlayoutparams (); intChildwidthspec = Getchildmeasurespec (widthmeasurespec, 0, Lp.width); intChildheightspec = Getchildmeasurespec (heightmeasurespec, 0, Lp.height);        Child.measure (Childwidthspec, Childheightspec); }        Switch(widthmode) { CaseMeasureSpec.EXACTLY:width=widthsize;  Break;  CaseMeasurespec.at_most: Casemeasurespec.unspecified: for(inti = 0; i < ChildCount; i++) {View child=Getchildat (i); intWidthaddoffset = i * OFFSET +child.getmeasuredwidth (); Width=Math.max (width, widthaddoffset); }                 Break; default:                 Break; }        Switch(heightmode) { CaseMeasureSpec.EXACTLY:height=heightsize;  Break;  CaseMeasurespec.at_most: Casemeasurespec.unspecified: for(inti = 0; i < ChildCount; i++) {View child=Getchildat (i); Height= height +child.getmeasuredheight (); }                 Break; default:                 Break;    } setmeasureddimension (width, height); } @Overrideprotected voidOnLayout (BooleanChangedintLintTintRintb) {intleft = 0; intright = 0; inttop = 0; intBottom = 0; intChildCount =Getchildcount ();  for(inti = 0; i < ChildCount; i++) {View child=Getchildat (i); Left= i *OFFSET; Right= left +child.getmeasuredwidth (); Bottom= Top +child.getmeasuredheight ();            Child.layout (left, top, right, bottom); Top+=child.getmeasuredheight (); }    }}



Layout mechanism of Android view frame

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.