View 繪製體系知識梳理(6) 繪製過程之 requestLayout 和 invalidate 詳解

澤毛發表於2017-12-21

一、概述

經過前面三篇文章的分析:

對於繪製的整個分發過程已經有了一個大致的瞭解,我們可以發現一個規律,無論是測量、佈局還是繪製,對於任何一個View/Group來說,它都是一個至上而下的遞迴事件呼叫,直到到達整個View樹的葉節點為止。 下面,我們來分析幾個平時常用的方法:

  • requestLayout
  • invalidate
  • postInvalidate

二、requestLayout

requestLayout是在View中定義的,並且在ViewGroup中沒有重寫該方法,它的註釋是這樣解釋的:在需要重新整理View的佈局時呼叫這個函式,它會安排一個佈局的傳遞。我們不應該在佈局的過程中(isInLayout())呼叫這個函式,如果當前正在佈局,那麼這一請求有可能在以下時刻被執行:當前佈局結束、當前幀被繪製完或者下次佈局發生時。

    /**
     * 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.
     *
     * <p>Subclasses which override this method should call the superclass method to
     * handle possible request-during-layout errors correctly.</p>
     */
    @CallSuper
    public void requestLayout() {
        if (mMeasureCache != null) mMeasureCache.clear();

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

        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
        mPrivateFlags |= PFLAG_INVALIDATED;

        if (mParent != null && !mParent.isLayoutRequested()) {
            mParent.requestLayout();
        }
        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
            mAttachInfo.mViewRequestingLayout = null;
        }
    }
複製程式碼

在上面的程式碼當中,設定了兩個標誌位:PFLAG_FORCE_LAYOUT/PFLAG_INVALIDATED,除此之外最關鍵的一句話是:

protected ViewParent mParent;
//....
mParent.requestLayout();
複製程式碼

這個mParent儲存的時候該View所對應的父節點,而當呼叫父節點的requestLayout()時,它又會呼叫它的父節點的requestLayout,就這樣,以呼叫requestLayoutView為起始節點,一步步沿著View樹傳遞上去,那麼這個過程什麼時候會終止呢? 根據前面的分析,我們知道整個View樹的根節點是DecorView,那麼我們需要看一下DecorViewmParent變數是什麼,回到ViewRootImplsetView方法當中,有這麼一句:

view.assignParent(this);
複製程式碼

因此,DecorView中的mParent就是ViewRootImpl,而ViewRootImpl中的mView就是DecorView,所以,這一傳遞過程的終點就是ViewRootImplrequestLayout方法:

    //ViewRootImpl中的requestLayout方法.
    @Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }

    void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            //該Runnable進行操作doTraversal.
            mChoreographer.postCallback(Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }

    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;
            }
        }
    }
複製程式碼

其中scheduleTraversals()中會執行一個mTraversalRunnable,該Runnable中最終會呼叫doTraversal,而doTraversal中執行的就是我們前面一直在談到的performTraversals。 那麼,前面我們分析過,performTraversalsmeasure方法會從根節點呼叫子節點的測量操作,並依次傳遞下去,那麼是否所有的子View都有必要重新測量呢,這就需要我們在呼叫ViewrequestLayout是設定的標誌位PFLAG_FORCE_LAYOUT來判斷,在measure當中,呼叫onMeasure之前,會有這麼一個判斷條件:

if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
                widthMeasureSpec != mOldWidthMeasureSpec ||
                heightMeasureSpec != mOldHeightMeasureSpec) {
    onMeasure(widthMeasureSpec, heightMeasureSpec);
}
複製程式碼

這個標誌位會在layout完成之後被恢復:

    public void layout(int l, int t, int r, int b) {
        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);
        }
        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
    }
複製程式碼

在進行完layout之後,requestLayout()所引發的過程就此終止了,它不會呼叫draw,不會重新繪製任何檢視包括該呼叫者本身。

三、invalidate

invalidate最終會呼叫到下面這個方法:

    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
            boolean fullInvalidate) {
        if (mGhostView != null) {
            mGhostView.invalidate(true);
            return;
        }

        if (skipInvalidate()) {
            return;
        }

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

            mPrivateFlags |= PFLAG_DIRTY;

            if (invalidateCache) {
                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);
                p.invalidateChild(this, damage);
            }

            // Damage the entire projection receiver, if necessary.
            if (mBackground != null && mBackground.isProjected()) {
                final View receiver = getProjectionReceiver();
                if (receiver != null) {
                    receiver.damageInParent();
                }
            }

            // Damage the entire IsolatedZVolume receiving this view's shadow.
            if (isHardwareAccelerated() && getZ() != 0) {
                damageShadowReceiver();
            }
        }
    }
複製程式碼

其中,關鍵的一句是:

p.invalidateChild(this, damage);
複製程式碼

在這裡,p一定不為空並且它一定是一個ViewGroup,那麼我們來看一下ViewGroup的這個方法:

public final void invalidateChild(View child, final Rect dirty) {
    do {
        parent = parent.invalidateChildInParent(location, dirty);
    } while (parent != null);
}
複製程式碼

ViewGroup當中的invalidateChildInParent會根據傳入的區域來決定自己的繪製區域,和requestLayout類似,最終會呼叫ViewRootImpl的該方法:

    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        checkThread();
        if (DEBUG_DRAW) Log.v(TAG, "Invalidate child: " + dirty);

        if (dirty == null) {
            invalidate();
            return null;
        } else if (dirty.isEmpty() && !mIsAnimating) {
            return null;
        }

        if (mCurScrollY != 0 || mTranslator != null) {
            mTempRect.set(dirty);
            dirty = mTempRect;
            if (mCurScrollY != 0) {
                dirty.offset(0, -mCurScrollY);
            }
            if (mTranslator != null) {
                mTranslator.translateRectInAppWindowToScreen(dirty);
            }
            if (mAttachInfo.mScalingRequired) {
                dirty.inset(-1, -1);
            }
        }
        invalidateRectOnScreen(dirty);
        return null;
    }
複製程式碼

這其中又會呼叫invalidate

    void invalidate() {
        mDirty.set(0, 0, mWidth, mHeight);
        if (!mWillDrawSoon) {
            scheduleTraversals();
        }
    }
複製程式碼

這裡,最終又會走到前面說的performTraversals()方法,請求重繪View樹,即draw()過程,假如檢視發生大小沒有變化就不會呼叫layout()過程,並且只繪製那些需要重繪的檢視。

三、其它知識點

  • invalidate,請求重新draw,只會繪製呼叫者本身。
  • setSelection,同上。
  • setVisibility:當ViewINVISIBLE變為VISIBILE,會間接呼叫invalidate方法,繼而繪製該View,而從INVISIBLE/VISIBLE變為GONE之後,由於View樹的大小發生了變化,會進行measure/layout/draw,同樣,他只會繪製需要重繪的檢視。
  • setEnable:請求重新draw,只會繪製呼叫者本身。
  • requestFocus:請求重新draw,只會繪製需要重繪的檢視。

四、參考文獻

1.http://blog.csdn.net/yanbober/article/details/46128379/ 2.http://blog.csdn.net/a553181867/article/details/51583060

相關文章