天天看點

自定義View原理篇(2)- layout過程1. 簡介2. layout的始點3.layout過程分析4. 自定義View5. 其他

1. 簡介

  • View

    的繪制過程分為三部分:

    measure

    layout

    draw

measure

用來測量View的寬和高。

layout

用來計算View的位置。

draw

用來繪制View。
  • 經過

    measure

    之後就進入了

    layout

    過程,

    measure

    過程可以檢視這篇文章:自定義View原理篇(1)-measure過程。
  • 本章主要對

    layout

    過程進行詳細的分析。
  • 本文源碼基于android 27。

2. layout的始點

measure

一樣,

layout

也是始于

ViewRootImpl

performTraversals()

:

2.1 ViewRootImpl的performTraversals

private void performTraversals() {
    
        //...
        
        //獲得view寬高的測量規格,mWidth和mHeight表示視窗的寬高,lp.widthhe和lp.height表示DecorView根布局寬和高
        int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
        int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);//執行測量
        
        //...
        
        performLayout(lp, mWidth, mHeight);//執行布局
        
        //...
        
        performDraw();//執行繪制
        
        //...
    }
           

再來看看

performLayout()

:

2.2 ViewRootImpl的performLayout

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
            
        //...
        
        //調用layout
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());

        //...
    }
           

這裡的

host

就是

DecorView

,如果不知道

DecorView

,可以看看這篇文章:從setContentView揭開DecorView。

layout()

方法傳入的

0,0,host.getMeasuredWidth,host.getMeasuredHeight

就是一個

View

的上下左右四個位置,可以看到,

DecorView

都是從左上角位置(0,0)開始進行布局的,其寬高則為測量寬高。

下面重點來分析

Layout

過程

3.layout過程分析

layout

用來計算

View

的位置,即确定

View

Left

Top

Right

Bottom

這四個頂點的位置。如下圖所示:

[外鍊圖檔轉存失敗(img-nd7ZrEmp-1568000248117)(http://upload-images.jianshu.io/upload_images/6163786-452eb2cc673d8ab0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]

同樣,

layout

過程根據

View

的類型也可以分為兩種情況:

  1. 計算單一

    View

    位置時,隻需計算其自身即可;
  2. 計算

    ViewGroup

    位置時,需要計算

    ViewGroup

    自身的位置以及其包含的子

    View

    ViewGroup

    中的位置。

我們對這兩種情況分别進行分析。

3.1 單一View的layout過程

單一

View

layout

過程是從

View

layout()

方法開始:

3.1.1 View的layout

public void layout(int l, int t, int r, int b) {
        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }

        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;
        
        //isLayoutModeOptical(mParent);//判斷該view布局模式是否有一些特殊的邊界
        //有特殊邊界則調用setOpticalFrame(l, t, r, b)
        //無特殊邊界則調用setFrame(l, t, r, b)
        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        // 若View的大小或位置有變化
        // 會重新确定該View所有的子View在父容器的位置,通過調用onLayout()來實作。
        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);

        // ...
    }
           

我們接下來分别看看

setOpticalFrame()

setFrame()

onLayout()

這三個方法。

3.1.2 View的setOpticalFrame

先來看看

setOpticalFrame()

private boolean setOpticalFrame(int left, int top, int right, int bottom) {
        Insets parentInsets = mParent instanceof View ?
                ((View) mParent).getOpticalInsets() : Insets.NONE;
        Insets childInsets = getOpticalInsets();
        
        //調用setFrame()
        return setFrame(
                left   + parentInsets.left - childInsets.left,
                top    + parentInsets.top  - childInsets.top,
                right  + parentInsets.left + childInsets.right,
                bottom + parentInsets.top  + childInsets.bottom);
    }
           

setOpticalFrame()

裡面最終還是會調用到

setFrame()

3.1.3 View的setFrame

protected boolean setFrame(int left, int top, int right, int bottom) {
        boolean changed = false;
        
        //...
        
        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
            changed = true;

            //...

            //指派,儲存View的四個位置
            mLeft = left;
            mTop = top;
            mRight = right;
            mBottom = bottom;
            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);

            //...
        }
        return changed;
    }
           

可以看到,

View

的四個位置就在這裡給确定下來了。

3.1.4 View的onLayout

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    }
           

onLayout()

View

中就是個空實作,由于單一的

View

沒有子

View

,是以不需要确定子

View

的布局,是以

onLayout()

也無需實作。

3.1.5 單一View的layout過程流程圖

是以,單一

View

Layout

還是很簡單的,來張流程圖簡單總結一下:

自定義View原理篇(2)- layout過程1. 簡介2. layout的始點3.layout過程分析4. 自定義View5. 其他

3.2 ViewGroup的layout過程

ViewGroup

layout

過程除了需要計算

ViewGroup

自身的位置外,還需要計算其包含的子

View

ViewGroup

中的位置。

計算

ViewGroup

自身的位置實際上跟單一

View

的過程是一樣的,這裡就不重述;唯一不同的就是單一

View

onLayout()

實作為空,

ViewGroup

需要具體實作

onLayout()

方法。

onLayout()

方法在

ViewGroup

是一個抽象方法,需要其子類去重寫,因為确定子

View

的位置與具體的布局有關,是以

ViewGroup

中沒有辦法統一實作。

我們在這裡看看

LinearLayout

onLayout()

實作:

3.2.1 LinearLayout的onLayout

@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (mOrientation == VERTICAL) {//方向判斷
            layoutVertical(l, t, r, b);
        } else {
            layoutHorizontal(l, t, r, b);
        }
    }
           

LinearLayout

會區分方向來進行不同的

layout

方法,我們主要看下豎向的

layoutVertical()

,橫向的原理差不多這裡就不看了。

3.2.2 LinearLayout的layoutVertical

void layoutVertical(int left, int top, int right, int bottom) {
        final int paddingLeft = mPaddingLeft;

        int childTop;//記錄子View的Top位置
        int childLeft;//記錄子View的Left位置

        // ...
        
        // 子View的數量
        final int count = getVirtualChildCount();

        // ...

        for (int i = 0; i < count; i++) {//周遊子View
            final View child = getVirtualChildAt(i);
            if (child == null) {
                childTop += measureNullChild(i);
            } else if (child.getVisibility() != GONE) {
            
                //擷取子View的測量寬 / 高值
                final int childWidth = child.getMeasuredWidth();
                final int childHeight = child.getMeasuredHeight();

                //...
                
                //childTop加上子View的topMargin的值
                childTop += lp.topMargin;
                
                //調用setChildFrame(),這裡确定子View的位置
                setChildFrame(child, childLeft, childTop + getLocationOffset(child),
                        childWidth, childHeight);
                        
                //childTop加上子View的高度、bottomMargin等值
                //是以後面的子View就順延往下放,這符合垂直方向的LinearLayout的特性
                childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);

                //...
            }
        }
    }
           

layoutVertical()

通過周遊子

View

,并調用

setChildFrame()

方法來确定子

View

的位置。

3.2.3 LinearLayout的setChildFrame

private void setChildFrame(View child, int left, int top, int width, int height) {
        child.layout(left, top, left + width, top + height);
    }
           

setChildFrame()

中就是調用子

View

layout()

方法來來确定子

View

的位置。

3.2.4 ViewGroup的layout過程流程圖

自定義View原理篇(2)- layout過程1. 簡介2. layout的始點3.layout過程分析4. 自定義View5. 其他

4. 自定義View

4.1 自定義單一view

自定義單一

view

一般無需重寫

onLayout()

方法。

4.2 自定義ViewGroup

由于

ViewGroup

沒實作

onLayout()

,是以自定義

ViewGroup

需要重寫

onLayout()

方法。這裡給個簡單的模闆:

@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        //周遊子View
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);

            //擷取目前子View寬/高值
            int width = child.getMeasuredWidth();
            int height = child.getMeasuredHeight();
            
            //計算目前子View的四個位置值
            int mLeft = l + 100 * i;//具體邏輯請自行計算
            int mTop = t + 100 * i;//具體邏輯請自行計算
            int mRight = mLeft + width;//具體邏輯請自行計算
            int mBottom = mTop + height;//具體邏輯請自行計算
            
            //根據上面的計算結果設定子View的4個頂點
            child.layout(mLeft, mTop, mRight, mBottom);
        }
    }
           

5. 其他

5.1 getWidth()與getMeasuredWidth()差別,getHeight()與getMeasuredHeight()同理

  • getWidth()

    :獲得

    View

    最終的寬;
  • getMeasuredWidth()

    :獲得

    View

    測量的寬;

一般情況下,這兩者獲得的值是一樣的,我們可以來看看他們的代碼實作:

public final int getMeasuredWidth() {
        return mMeasuredWidth & MEASURED_SIZE_MASK;
    }
    
    public final int getWidth() {
        return mRight - mLeft;
    }
           

結合源碼中的各種指派過程,

getWidth()

的值就是測量出的寬度。

當然,我們可以通過重寫

layout()

來修改最終的寬度,但一般這沒有任何的實際意義,如:

@Override
    public void layout(int l, int t, int r, int b) {

        // 修改傳入的位置參數,這樣一來,getWidth()獲得的寬度就比測量出來的寬度大上100了
        super.layout(l, t, r + 100, b + 100);
    }