自定義View的流程分析

自定義View的流程,requestLayout和invalidate的區(qū)別

流程

一般來(lái)說(shuō),自定義view分為兩種方式:一種是繼承自某個(gè)特定的View或容器,如ImageView,TestView,FrameLayout等;在該View基礎(chǔ)上做一些功能/樣式的自定義;另一種是直接繼承自View,或ViewGroup,實(shí)現(xiàn)對(duì)應(yīng)功能/樣式。

不管是上面那種方式,都會(huì)涉及到自定義View的requestLayout方法,invalidate方法,
以及onMeasure、onLayoutonDraw方法

我們先看看requestLayout方法的源碼:

requestLayout方法

    /**
     * Call this when something has changed which has invalidated the
     * layout of this view. This will schedule a layout pass of the view
     * tree. This should not be called while the view hierarchy is currently in a layout
     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
     * end of the current layout pass (and then layout will run again) or after the current
     * frame is drawn and the next layout occurs.
     * 
     *  當(dāng)某些更改使該視圖的布局無(wú)效時(shí),調(diào)用此方法。這將安排視圖樹(shù)的布局遍歷。當(dāng)視圖層次結(jié)構(gòu)當(dāng)前處于布局階段
     *({@link #isInLayout()}中時(shí),不應(yīng)調(diào)用此方法。如果正在進(jìn)行布局,則可以在當(dāng)前布局階段結(jié)束時(shí)接受請(qǐng)求
     *(然后布局將再次運(yùn)行) )或繪制當(dāng)前幀并進(jìn)行下一個(gè)布局之后。
     *
     * <p>Subclasses which override this method should call the superclass method to
     * handle possible request-during-layout errors correctly.</p>
     * 
     * 覆蓋此方法的子類應(yīng)調(diào)用超類方法以正確處理可能的request-during-layout錯(cuò)誤。
     */
    @CallSuper
    public void requestLayout() {
        //測(cè)量緩存清理
        if (mMeasureCache != null) mMeasureCache.clear();
        //判斷當(dāng)前view/layout是否被綁定,即是否存在ViewRoot
        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
            // Only trigger request-during-layout logic if this is the view requesting it,
            // not the views in its parent hierarchy
            ViewRootImpl viewRoot = getViewRootImpl();
            if (viewRoot != null && viewRoot.isInLayout()) {
                if (!viewRoot.requestLayoutDuringLayout(this)) {
                    return;
                }
            }
            mAttachInfo.mViewRequestingLayout = this;
        }
        //設(shè)置View的標(biāo)記位,
        //PFLAG_FORCE_LAYOUT表示當(dāng)前View要進(jìn)行重新布局;
        //PFLAG_INVALIDATED表示要進(jìn)行重新繪制。
        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
        mPrivateFlags |= PFLAG_INVALIDATED;

        //逐層向上調(diào)用父布局的requestLayout方法
        if (mParent != null && !mParent.isLayoutRequested()) {
            mParent.requestLayout();
        }
        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
            mAttachInfo.mViewRequestingLayout = null;
        }
    }

分析

  1. 在View的requestLayout方法中,首先會(huì)設(shè)置View的標(biāo)記位;
    • PFLAG_FORCE_LAYOUT表示當(dāng)前View要進(jìn)行重新布局;
    • PFLAG_INVALIDATED表示要進(jìn)行重新繪制。
  2. requestLayout方法會(huì)逐層層向上調(diào)用父布局的requestLayout方法,設(shè)置PFLAG_FORCE_LAYOUT標(biāo)記,最終調(diào)用的是ViewRootImpl中的requestLayout方法

ViewRootImpl中的requestLayout方法

    @Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }

在 ViewRootImpl中的requestLayout方法中可以看到requestLayout方法中會(huì)調(diào)用scheduleTraversals方法; 來(lái)看看scheduleTraversals;

ViewRootImpl中的 scheduleTraversals 方法

    void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            //設(shè)置同步屏障
            //同步屏障只在Looper死循環(huán)獲取待處理消息時(shí)才會(huì)起作用,也就是說(shuō)同步屏障在MessageQueue.next函數(shù)中發(fā)揮著作用。
            //換句話說(shuō)就是,設(shè)置了同步屏障之后,Handler只會(huì)處理異步消息。再換句話說(shuō),同步屏障為Handler消息機(jī)制增加了一種簡(jiǎn)單的優(yōu)先級(jí)機(jī)制,異步消息的優(yōu)先級(jí)要高于同步消息
            mTraversalBarrier =
            mHandler.getLooper().getQueue().postSyncBarrier();
            //調(diào)用編排器的postCallback來(lái)傳入mTraversalRunnable
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }

注:

同步屏障--- 同步屏障只在Looper死循環(huán)獲取待處理消息時(shí)才會(huì)起作用,也就是說(shuō)同步屏障在MessageQueue.next函數(shù)中發(fā)揮著作用。
換句話說(shuō)就是,設(shè)置了同步屏障之后,Handler只會(huì)處理異步消息。再換句話說(shuō),同步屏障為Handler消息機(jī)制增加了一種簡(jiǎn)單的優(yōu)先級(jí)機(jī)制,異步消息的優(yōu)先級(jí)要高于同步消息

編排器--- 協(xié)調(diào)動(dòng)畫,輸入和繪圖的時(shí)間。
編排人員從顯示子系統(tǒng)接收定時(shí)脈沖(例如垂直同步),然后安排工作以進(jìn)行渲染下一個(gè)顯示幀的一部分。
應(yīng)用程序通常使用動(dòng)畫框架或視圖層次結(jié)構(gòu)中的更高級(jí)別的抽象間接與編排器交互。

  • 在scheduleTraversals 方法中先設(shè)置了handler的同步屏障
  • 調(diào)用編排器的postCallback傳入一個(gè)可執(zhí)行的Runnable實(shí)例mTraversalRunnable,等待執(zhí)行mTraversalRunnable

** TraversalRunnable 實(shí)例**

    final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
    
    void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);

            if (mProfile) {
                Debug.startMethodTracing("ViewAncestor");
            }

            performTraversals();

            if (mProfile) {
                Debug.stopMethodTracing();
                mProfile = false;
            }
        }
    }
    
    

  • 在TraversalRunnable的run方法中,調(diào)用了doTraversal()方法
  • doTraversal()方法中,先移除調(diào)同步屏障,然后調(diào)用了performTraversals()方法。

performTraversals()方法

    private void performTraversals() {
        //初始化一些屬性值,設(shè)置windows
        //......
        
        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
        
        //......
        
        performLayout(lp, mWidth, mHeight);
        
        //...... 
        
        performDraw();
        
    }

  • performTraversals()方法中有幾百上千行代碼,這里省略調(diào)大部分,只留下三個(gè)方法,在該方法執(zhí)行過(guò)程中,分布調(diào)用了performMeasure方法,performLayout方法和performDraw方法
  • performMeasure方法,performLayout方法中會(huì)分別調(diào)用view的measure方法,layout方法
  • performDraw方法會(huì)調(diào)用當(dāng)前類中的draw方法
  • draw方法會(huì)調(diào)用當(dāng)前view的綁定信息中的view樹(shù)中的dispatchOnDraw:mAttachInfo.mTreeObserver.dispatchOnDraw();
  • dispatchOnDraw()方法中最后調(diào)用了drawSoftware方法,
  • drawSoftware方法中通過(guò)mSurface.lockCanvas((Rect)dirty)獲取到了surface的canvas對(duì)象
  • 調(diào)用了mView.draw(canvas)方法,開(kāi)始執(zhí)行draw操作

view的measure方法

 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
       //......
        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
        //......
        
        if (forceLayout || needsLayout) {
            // first clears the measured dimension flag
            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;

            resolveRtlPropertiesIfNeeded();

            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } else {
                long value = mMeasureCache.valueAt(cacheIndex);
                // Casting a long to int drops the high 32 bits, no mask needed
                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            }

            //...
            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
        }

        //...
    }
  • 由于requestLayout方法設(shè)置了PFLAG_FORCE_LAYOUT標(biāo)記位,所以measure方法就會(huì)調(diào)用onMeasure方法對(duì)View進(jìn)行重新測(cè)量
  • 在measure方法中最后設(shè)置了PFLAG_LAYOUT_REQUIRED標(biāo)記位,這樣在layout方法中就會(huì)執(zhí)行onLayout方法進(jìn)行布局流程

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

        //...
        //measure方法中設(shè)置了PFLAG_LAYOUT_REQUIRED標(biāo)記位,所以會(huì)進(jìn)入調(diào)用onLayout方法進(jìn)行布局流程
        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);

            if (shouldDrawRoundScrollbar()) {
                if(mRoundScrollbarRenderer == null) {
                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
                }
            } else {
                mRoundScrollbarRenderer = null;
            }

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

        final boolean wasLayoutValid = isLayoutValid();

        //取消PFLAG_FORCE_LAYOUT標(biāo)記位
        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;

        //......
        
    }
  • measure方法中設(shè)置了 PFLAG_LAYOUT_REQUIRED標(biāo)記位,所以在layout方法中onLayout方法會(huì)被調(diào)用執(zhí)行布局流程
  • 清除PFLAG_FORCE_LAYOUT和PFLAG_LAYOUT_REQUIRED標(biāo)記位

view的draw方法

    public void draw(Canvas canvas) {
        //......
        // 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);

            drawAutofilledHighlight(canvas);

            // Overlay is part of the content and draws beneath Foreground
            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // Step 6, draw decorations (foreground, scrollbars)
            onDrawForeground(canvas);

            // Step 7, draw the default focus highlight
            drawDefaultFocusHighlight(canvas);
            
        }
        //......
    }

  • 在view的draw方法中會(huì)根據(jù)需要,按照順序調(diào)用7個(gè)步驟
      1. drawBackground(canvas): 畫背景
      1. 如有必要,保存畫布的圖層以準(zhǔn)備褪色
      1. onDraw(canvas): 繪制視圖的內(nèi)容
      1. dispatchDraw(canvas): 繪制子視圖
      1. 如有必要,繪制褪色邊緣并恢復(fù)圖層
      1. onDrawForeground(canvas):繪制裝飾(例如滾動(dòng)條)
      1. drawDefaultFocusHighlight(canvas): 在畫布上繪制默認(rèn)的焦點(diǎn)突出顯示。

總結(jié)

  1. requestLayout方法會(huì)標(biāo)記PFLAG_FORCE_LAYOUT,然后一層層往上調(diào)用父布局的requestLayout方法并標(biāo)記PFLAG_FORCE_LAYOUT
  2. 調(diào)用ViewRootImpl中的requestLayout方法開(kāi)始View的三大流程
  3. 被標(biāo)記的View會(huì)進(jìn)行測(cè)量、布局和繪制流程,調(diào)用方法onMeasure、onLayout和onDraw

invalidate方法

invalidate方法 通過(guò)層層調(diào)用,最終調(diào)用了view類中的invalidateInternal方法``

view類中的invalidateInternal方法``

    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
            boolean fullInvalidate) {
       //...

        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
            if (fullInvalidate) {
                mLastIsOpaque = isOpaque();
                mPrivateFlags &= ~PFLAG_DRAWN;
            }

            //設(shè)置View的標(biāo)記位,
            //PFLAG_INVALIDATED 視圖標(biāo)志,指示此視圖是無(wú)效的(全部或部分無(wú)效)。
            mPrivateFlags |= PFLAG_DIRTY;

            if (invalidateCache) {
             //PFLAG_INVALIDATED表示要進(jìn)行重新繪制。
                mPrivateFlags |= PFLAG_INVALIDATED;
                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
            }

            // Propagate the damage rectangle to the parent view.
            final AttachInfo ai = mAttachInfo;
            final ViewParent p = mParent;
            if (p != null && ai != null && l < r && t < b) {
                final Rect damage = ai.mTmpInvalRect;
                damage.set(l, t, r, b);
                //調(diào)用ViewRootImpl中的invalidateChild方法
                p.invalidateChild(this, damage);
            }

           //...
        }
    }

ViewRootImpl中的invalidateChild方法

@Override
    public void invalidateChild(View child, Rect dirty) {
        invalidateChildInParent(null, dirty);
    }

    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        //...
        if (dirty == null) {
            invalidate();
            return null;
        } else if (dirty.isEmpty() && !mIsAnimating) {
            return null;
        }
        //...
        invalidateRectOnScreen(dirty);
        return null;
    }
    
    void invalidate() {
        mDirty.set(0, 0, mWidth, mHeight);
        if (!mWillDrawSoon) {
            scheduleTraversals();
        }
    }
    
    
    private void invalidateRectOnScreen(Rect dirty) {
        //...
        if (!mWillDrawSoon && (intersected || mIsAnimating)) {
            scheduleTraversals();
        }
    }

分析

可以看到invalidate方法最終還是調(diào)用了 ViewRootImpl 類中的scheduleTraversals()方法,該方法在上面看requestLayout方法的時(shí)候已經(jīng)看過(guò)了,就不在貼代碼了

總結(jié)

  1. invalidate方法過(guò)程和requestLayout方法很像,最終都執(zhí)行了scheduleTraversals()方法;
  2. invalidate方法沒(méi)有標(biāo)記PFLAG_FORCE_LAYOUT,所以不會(huì)執(zhí)行測(cè)量和布局流程,只是對(duì)需要重繪的View進(jìn)行重繪,也就是只會(huì)調(diào)用onDraw方法,不會(huì)調(diào)用onMeasure和onLayout方法。
  3. invalidate方法只能在UI線程調(diào)用,不能在非UI線程調(diào)用

postInvalidate方法

postInvalidate方法可以在非UI線程調(diào)用,其內(nèi)部在調(diào)用了ViewRootImpl的dispatchInvalidateDelayed(View view, long delayMilliseconds)方法,在此方法中通過(guò)Handler,進(jìn)行線程切換,最終在UI線程中調(diào)用invalidate方法

ViewRootImpl的dispatchInvalidateDelayed(View view, long delayMilliseconds)方法

    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
        mHandler.sendMessageDelayed(msg, delayMilliseconds);
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容