自定義View原理篇(2)- layout過程

1. 簡介

  • View的繪制過程分為三部分:measurelayoutdraw饱狂。

measure用來測量View的寬和高。
layout用來計算View的位置宪彩。
draw用來繪制View休讳。

  • 經(jīng)過measure之后就進入了layout過程,measure過程可以查看這篇文章:自定義View原理篇(1)- measure過程尿孔。

  • 本章主要對layout過程進行詳細的分析俊柔。

  • 本文源碼基于android 27

2. layout的始點

measure一樣,layout也是始于ViewRootImplperformTraversals():

2.1 ViewRootImpl的performTraversals

    private void performTraversals() {

        //...

        //獲得view寬高的測量規(guī)格活合,mWidth和mHeight表示窗口的寬高雏婶,lp.widthhe和lp.height表示DecorView根布局寬和高
        int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
        int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);//執(zhí)行測量

        //...

        performLayout(lp, mWidth, mHeight);//執(zhí)行布局

        //...

        performDraw();//執(zhí)行繪制

        //...
    }

再來看看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的位置憨闰,即確定ViewLeftTop需五、RightBottom這四個頂點的位置鹉动。如下圖所示:

image

同樣,layout過程根據(jù)View的類型也可以分為兩種情況:

  1. 計算單一View位置時宏邮,只需計算其自身即可泽示;
  2. 計算ViewGroup位置時,需要計算ViewGroup自身的位置以及其包含的子ViewViewGroup中的位置蜜氨。

我們對這兩種情況分別進行分析械筛。

3.1 單一View的layout過程

單一Viewlayout過程是從Viewlayout()方法開始:

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()來實現(xiàn)飒炎。
        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中就是個空實現(xiàn)抛计,由于單一的View沒有子View,因此不需要確定子View的布局照筑,所以onLayout()也無需實現(xiàn)吹截。

3.1.5 單一View的layout過程流程圖

所以,單一ViewLayout還是很簡單的凝危,來張流程圖簡單總結一下:

image

3.2 ViewGroup的layout過程

ViewGrouplayout過程除了需要計算ViewGroup自身的位置外波俄,還需要計算其包含的子ViewViewGroup中的位置。
計算ViewGroup自身的位置實際上跟單一View的過程是一樣的蛾默,這里就不重述;唯一不同的就是單一ViewonLayout()實現(xiàn)為空懦铺,ViewGroup需要具體實現(xiàn)onLayout()方法。

onLayout()方法在ViewGroup是一個抽象方法趴生,需要其子類去重寫阀趴,因為確定子View的位置與具體的布局有關,所以ViewGroup中沒有辦法統(tǒng)一實現(xiàn)苍匆。

我們在這里看看LinearLayoutonLayout()實現(xiàn):

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會區(qū)分方向來進行不同的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的數(shù)量
        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()中就是調用子Viewlayout()方法來來確定子View的位置。

3.2.4 ViewGroup的layout過程流程圖

image

4. 自定義View

4.1 自定義單一view

自定義單一view一般無需重寫onLayout()方法另假。

4.2 自定義ViewGroup

由于ViewGroup沒實現(xiàn)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;//具體邏輯請自行計算

            //根據(jù)上面的計算結果設置子View的4個頂點
            child.layout(mLeft, mTop, mRight, mBottom);
        }
    }

5. 其他

5.1 getWidth()與getMeasuredWidth()區(qū)別边篮,getHeight()與getMeasuredHeight()同理

  • getWidth():獲得View最終的寬;
  • getMeasuredWidth():獲得View測量的寬;

一般情況下己莺,這兩者獲得的值是一樣的,我們可以來看看他們的代碼實現(xiàn):

    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) {

        // 修改傳入的位置參數(shù),這樣一來色乾,getWidth()獲得的寬度就比測量出來的寬度大上100了
        super.layout(l, t, r + 100, b + 100);
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末誊册,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子杈湾,更是在濱河造成了極大的恐慌解虱,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件漆撞,死亡現(xiàn)場離奇詭異,居然都是意外死亡于宙,警方通過查閱死者的電腦和手機浮驳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來捞魁,“玉大人至会,你說我怎么就攤上這事∑准螅” “怎么了奉件?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長昆著。 經(jīng)常有香客問我县貌,道長,這世上最難降的妖魔是什么凑懂? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任煤痕,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘摆碉。我一直安慰自己塘匣,他們只是感情好,可當我...
    茶點故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布巷帝。 她就那樣靜靜地躺著忌卤,像睡著了一般。 火紅的嫁衣襯著肌膚如雪楞泼。 梳的紋絲不亂的頭發(fā)上埠巨,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天,我揣著相機與錄音现拒,去河邊找鬼辣垒。 笑死,一個胖子當著我的面吹牛印蔬,可吹牛的內容都是我干的勋桶。 我是一名探鬼主播,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼侥猬,長吁一口氣:“原來是場噩夢啊……” “哼例驹!你這毒婦竟也來了?” 一聲冷哼從身側響起退唠,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤鹃锈,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后瞧预,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體屎债,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年垢油,在試婚紗的時候發(fā)現(xiàn)自己被綠了盆驹。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡滩愁,死狀恐怖躯喇,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情硝枉,我是刑警寧澤廉丽,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站妻味,受9級特大地震影響正压,放射性物質發(fā)生泄漏。R本人自食惡果不足惜弧可,卻給世界環(huán)境...
    茶點故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一蔑匣、第九天 我趴在偏房一處隱蔽的房頂上張望劣欢。 院中可真熱鬧,春花似錦裁良、人聲如沸凿将。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽牧抵。三九已至,卻和暖如春侨把,著一層夾襖步出監(jiān)牢的瞬間犀变,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工秋柄, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留获枝,地道東北人。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓骇笔,卻偏偏與公主長得像省店,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子笨触,可洞房花燭夜當晚...
    茶點故事閱讀 45,500評論 2 359