View 工作原理(三)| 藝術(shù)探索筆記

這里介紹 View 的 Layout 和 Draw 過程嘿歌。

Layout 過程

Layout 過程的作用是 ViewGroup 來確定子元素的位置掸掏,來看 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;
    boolean changed = isLayoutModeOptical(mParent) ?
        setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
    if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
        onLayout(changed, l, t, r, b);
        mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnLayoutChangeListeners != null) {
            ArrayList<OnLayoutChangeListener> listenersCopy =
                (ArrayList<OnLayoutChangeListener>) li.mOnLayoutChangeListeners.clone();
            int numListeners = listenersCopy.size();
            for (int i = 0; i < numListeners; ++i) {
                listenersCopy.get(i).onLayoutChange(
                    this, l, t, r, b, oldL, oldT, oldR, oldB);
            }
        }
    }
    mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
    mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}

首先通過 setFrame 方法來設(shè)定 View 四個頂點(diǎn)位置,分別是 mLeft宙帝、mRight丧凤、mTop、mBottom 的值步脓,四個頂點(diǎn)一旦確定愿待,View 在父容器的位置也就確定了。接著調(diào)用 onLayout 方法靴患,它用來確定子元素的位置仍侥。與 onMeasure 方法類似,View 和 ViewGroup 都沒有實現(xiàn) onLayout 方法鸳君,于是再次選擇 LinearLayout 的 onLayout 方法

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);
    }
}

由于 layoutVertical 與 layoutHorizontal 方法實現(xiàn)類似农渊,所以只看 layoutVertical 方法的主要代碼

void layoutVertical(int left, int top, int right, int bottom) {

    ...

    final int count = getVirtualChildCount();
    for (int i = 0; i < count; i++) {
        final View child = getVirtualChildAt(i);
        if (child == null) {
            childTop += measureNullChild(i);
        } else if (child.getVisibility() != GONE) {
            final int childWidth = child.getMeasuredWidth();
            final int childHeight = child.getMeasuredHeight();
            final LinearLayout.LayoutParams lp =
                (LinearLayout.LayoutParams) child.getLayoutParams();
        }

        ...

        if (hasDividerBeforeChildAt(i)) {
            childTop += mDividerHeight;
        }
        childTop += lp.topMargin;
        setChildFrame(child, childLeft, childTop + getLocationOffset(child),
            childWidth, childHeight);
        childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
        i += getChildrenSkipCount(child, i);
}

可以看到,layoutVertical 會遍歷所有子元素并調(diào)用 setChildFrame 方法來給子元素指定位置或颊,其中 childTop 會逐漸增大腿时,這意味元素會從上到下排列。

看下 setChildFrame 方法

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

setChildFrame 中僅僅是調(diào)用子元素的 layout 方法饭宾。其中 width 和 height 是子元素的測量寬高

final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
    childWidth, childHeight);

總結(jié)一下,父元素在 layout 方法中完成定位后格了,通過 onLayout 方法調(diào)用子元素的 layout 方法看铆,而子元素會通過 layout 方法來確定自己的位置,這樣一層層的傳遞就完成了 View 的 Layout 過程盛末。

View 工作原理(一)中有提到測量寬高大部分情況下等于最終寬高弹惦,之所以說大部分情況否淤,是因為測量寬高的賦值早于最終寬高,如果重寫 View 的 layout 方法

public void layout(int l, int t, int r, int b) {
    super.layout(l, t, r + 10, b + 10);
}

那么這種情況下棠隐,最終寬高不等于測量寬高石抡。另一種情況是,當(dāng) View 需要多次 measure 來測量寬高助泽,那么前幾次的測量值可能就不會與最終寬高相等啰扛。

Draw 過程

Draw 過程的作用是將 View 繪制到屏幕上,看 draw 方法

public void draw(Canvas canvas) {
    final int privateFlags = mPrivateFlags;
    final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) ==
        PFLAG_DIRTY_OPAQUE && (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
    mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;

    /*
    * Draw traversal performs several drawing steps which must be executed
    * in the appropriate order:
    *
    *      1. Draw the background
    *      2. If necessary, save the canvas' layers to prepare for fading
    *      3. Draw view's content
    *      4. Draw children
    *      5. If necessary, draw the fading edges and restore layers
    *      6. Draw decorations (scrollbars for instance)
    */

    // Step 1, draw the background, if needed
    int saveCount;

    if (!dirtyOpaque) {
        drawBackground(canvas);
    }

    // skip step 2 & 5 if possible (common case)
    final int viewFlags = mViewFlags;
    boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
    boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
    if (!verticalEdges && !horizontalEdges) {
        // Step 3, draw the content
        if (!dirtyOpaque) onDraw(canvas);

        // Step 4, draw the children
        dispatchDraw(canvas);

        // Step 6, draw decorations (scrollbars)
        onDrawScrollBars(canvas);

        if (mOverlay != null && !mOverlay.isEmpty()) {
            mOverlay.getOverlayView().dispatchDraw(canvas);
        }

        // we're done...
        return;
    }

    ...

}

于是得到主要步驟

  1. 繪制背景 drawBackground
  2. 繪制內(nèi)容 onDraw
  3. 繪制子元素 dispatchDraw
  4. 繪制裝飾 onDrawScrollBars

來看 drawBackground 方法

private void drawBackground(Canvas canvas) {
    final Drawable background = mBackground;
    if (background == null) {
        return;
    }
    setBackgroundBounds();

    ...

    final int scrollX = mScrollX;
    final int scrollY = mScrollY;
    if ((scrollX | scrollY) == 0) {
        background.draw(canvas);
    } else {
        canvas.translate(scrollX, scrollY);
        background.draw(canvas);
        canvas.translate(-scrollX, -scrollY);
    }
}

drawBackground 方法使用 scrollX 和 scrollY 記錄偏移值嗡贺,然后根據(jù)偏移值進(jìn)行繪制隐解。

由于 View 沒有實現(xiàn) onDraw 方法,所以先跳過诫睬。

在普通 View 中煞茫,因為它沒有子元素,所以 dispatchDraw 方法為空摄凡。于是看 ViewGroup 的 dispatchDraw 方法

protected void dispatchDraw(Canvas canvas) {

    ...

    for (int i = 0; i < childrenCount; i++) {
        int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i;
        final View child = (preorderedList == null)
            ? children[childIndex] : preorderedList.get(childIndex);
        if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE ||
            child.getAnimation() != null) {
            more |= drawChild(canvas, child, drawingTime);
        }
    }

    ...

}

protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
    return child.draw(canvas, this, drawingTime);
}

可以看到续徽,dispatchDraw 方法會遍歷所有子元素的 draw 方法,這樣就將 Draw 過程傳遞了下去亲澡。

最后通過 onDrawScrollBars 方法繪制完滾動條(滾動條可能不顯示)钦扭。這樣 View 的 Draw 過程就完成了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末谷扣,一起剝皮案震驚了整個濱河市土全,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌会涎,老刑警劉巖裹匙,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異末秃,居然都是意外死亡概页,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進(jìn)店門练慕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來惰匙,“玉大人,你說我怎么就攤上這事铃将∠罟恚” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵劲阎,是天一觀的道長绘盟。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么龄毡? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任吠卷,我火速辦了婚禮,結(jié)果婚禮上沦零,老公的妹妹穿的比我還像新娘祭隔。我一直安慰自己,他們只是感情好路操,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布疾渴。 她就那樣靜靜地躺著,像睡著了一般寻拂。 火紅的嫁衣襯著肌膚如雪程奠。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天祭钉,我揣著相機(jī)與錄音瞄沙,去河邊找鬼。 笑死慌核,一個胖子當(dāng)著我的面吹牛距境,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播垮卓,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼垫桂,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了粟按?” 一聲冷哼從身側(cè)響起诬滩,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎灭将,沒想到半個月后疼鸟,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡庙曙,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年空镜,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片捌朴。...
    茶點(diǎn)故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡吴攒,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出砂蔽,到底是詐尸還是另有隱情洼怔,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布左驾,位于F島的核電站茴厉,受9級特大地震影響泽台,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜矾缓,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望稻爬。 院中可真熱鬧嗜闻,春花似錦、人聲如沸桅锄。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽友瘤。三九已至翠肘,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間辫秧,已是汗流浹背束倍。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留盟戏,地道東北人绪妹。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像柿究,于是被迫代替她去往敵國和親邮旷。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容