自定義View的流程,requestLayout和invalidate的區別
流程
一般來說,自定義view分爲兩種方式:一種是繼承自某個特定的View或容器,如ImageView
,TestView
,FrameLayout
等;在該View基礎上做一些功能/樣式的自定義;另一種是直接繼承自View,或ViewGroup,實現對應功能/樣式。
不管是上面那種方式,都會涉及到自定義View的requestLayout
方法,invalidate
方法,
以及onMeasure
、onLayout
、onDraw
方法
我們先看看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.
*
* 當某些更改使該視圖的佈局無效時,調用此方法。這將安排視圖樹的佈局遍歷。當視圖層次結構當前處於佈局階段
*({@link #isInLayout()}中時,不應調用此方法。如果正在進行佈局,則可以在當前佈局階段結束時接受請求
*(然後佈局將再次運行) )或繪製當前幀並進行下一個佈局之後。
*
* <p>Subclasses which override this method should call the superclass method to
* handle possible request-during-layout errors correctly.</p>
*
* 覆蓋此方法的子類應調用超類方法以正確處理可能的request-during-layout錯誤。
*/
@CallSuper
public void requestLayout() {
//測量緩存清理
if (mMeasureCache != null) mMeasureCache.clear();
//判斷當前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;
}
//設置View的標記位,
//PFLAG_FORCE_LAYOUT表示當前View要進行重新佈局;
//PFLAG_INVALIDATED表示要進行重新繪製。
mPrivateFlags |= PFLAG_FORCE_LAYOUT;
mPrivateFlags |= PFLAG_INVALIDATED;
//逐層向上調用父佈局的requestLayout方法
if (mParent != null && !mParent.isLayoutRequested()) {
mParent.requestLayout();
}
if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
mAttachInfo.mViewRequestingLayout = null;
}
}
分析
- 在View的requestLayout方法中,首先會設置View的標記位;
- PFLAG_FORCE_LAYOUT表示當前View要進行重新佈局;
- PFLAG_INVALIDATED表示要進行重新繪製。
- requestLayout方法會逐層層向上調用父佈局的requestLayout方法,設置PFLAG_FORCE_LAYOUT標記,最終調用的是ViewRootImpl中的requestLayout方法
ViewRootImpl中的requestLayout方法
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
在 ViewRootImpl中的requestLayout方法中可以看到requestLayout方法中會調用scheduleTraversals方法; 來看看scheduleTraversals;
ViewRootImpl中的 scheduleTraversals 方法
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
//設置同步屏障
//同步屏障只在Looper死循環獲取待處理消息時纔會起作用,也就是說同步屏障在MessageQueue.next函數中發揮着作用。
//換句話說就是,設置了同步屏障之後,Handler只會處理異步消息。再換句話說,同步屏障爲Handler消息機制增加了一種簡單的優先級機制,異步消息的優先級要高於同步消息
mTraversalBarrier =
mHandler.getLooper().getQueue().postSyncBarrier();
//調用編排器的postCallback來傳入mTraversalRunnable
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
if (!mUnbufferedInputDispatch) {
scheduleConsumeBatchedInput();
}
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
}
注:
同步屏障--- 同步屏障只在Looper死循環獲取待處理消息時纔會起作用,也就是說同步屏障在MessageQueue.next函數中發揮着作用。
換句話說就是,設置了同步屏障之後,Handler只會處理異步消息。再換句話說,同步屏障爲Handler消息機制增加了一種簡單的優先級機制,異步消息的優先級要高於同步消息
編排器--- 協調動畫,輸入和繪圖的時間。
編排人員從顯示子系統接收定時脈衝(例如垂直同步),然後安排工作以進行渲染下一個顯示幀的一部分。
應用程序通常使用動畫框架或視圖層次結構中的更高級別的抽象間接與編排器交互。
- 在scheduleTraversals 方法中先設置了handler的同步屏障
- 調用編排器的postCallback傳入一個可執行的Runnable實例mTraversalRunnable,等待執行mTraversalRunnable
** TraversalRunnable 實例**
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方法中,調用了
doTraversal()
方法 - 在
doTraversal()
方法中,先移除調同步屏障,然後調用了performTraversals()
方法。
performTraversals()
方法
private void performTraversals() {
//初始化一些屬性值,設置windows
//......
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
//......
performLayout(lp, mWidth, mHeight);
//......
performDraw();
}
-
performTraversals()
方法中有幾百上千行代碼,這裏省略調大部分,只留下三個方法,在該方法執行過程中,分佈調用了performMeasure
方法,performLayout
方法和performDraw
方法 - 在
performMeasure
方法,performLayout
方法中會分別調用view的measure
方法,layout
方法 -
performDraw
方法會調用當前類中的draw
方法 -
draw
方法會調用當前view的綁定信息中的view樹中的dispatchOnDraw:mAttachInfo.mTreeObserver.dispatchOnDraw();
- 在
dispatchOnDraw()
方法中最後調用了drawSoftware
方法, - 在
drawSoftware
方法中通過mSurface.lockCanvas((Rect)dirty)
獲取到了surface的canvas
對象 - 調用了
mView.draw(canvas)
方法,開始執行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方法設置了
PFLAG_FORCE_LAYOUT
標記位,所以measure方法就會調用onMeasure
方法對View進行重新測量 - 在measure方法中最後設置了
PFLAG_LAYOUT_REQUIRED
標記位,這樣在layout方法中就會執行onLayout方法進行佈局流程
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方法中設置了PFLAG_LAYOUT_REQUIRED標記位,所以會進入調用onLayout方法進行佈局流程
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標記位
mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
//......
}
- measure方法中設置了
PFLAG_LAYOUT_REQUIRED
標記位,所以在layout方法中onLayout
方法會被調用執行佈局流程 - 清除PFLAG_FORCE_LAYOUT和PFLAG_LAYOUT_REQUIRED標記位
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方法中會根據需要,按照順序調用7個步驟
-
drawBackground(canvas)
: 畫背景
-
- 如有必要,保存畫布的圖層以準備褪色
-
onDraw(canvas)
: 繪製視圖的內容
-
-
dispatchDraw(canvas)
: 繪製子視圖
-
- 如有必要,繪製褪色邊緣並恢復圖層
-
onDrawForeground(canvas)
:繪製裝飾(例如滾動條)
-
-
drawDefaultFocusHighlight(canvas)
: 在畫布上繪製默認的焦點突出顯示。
-
總結
- requestLayout方法會標記
PFLAG_FORCE_LAYOUT
,然後一層層往上調用父佈局的requestLayout方法並標記PFLAG_FORCE_LAYOUT - 調用ViewRootImpl中的requestLayout方法開始View的三大流程
- 被標記的View會進行測量、佈局和繪製流程,調用方法onMeasure、onLayout和onDraw
invalidate
方法
invalidate
方法 通過層層調用,最終調用了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;
}
//設置View的標記位,
//PFLAG_INVALIDATED 視圖標誌,指示此視圖是無效的(全部或部分無效)。
mPrivateFlags |= PFLAG_DIRTY;
if (invalidateCache) {
//PFLAG_INVALIDATED表示要進行重新繪製。
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);
//調用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
方法最終還是調用了 ViewRootImpl 類中的scheduleTraversals()
方法,該方法在上面看requestLayout
方法的時候已經看過了,就不在貼代碼了
總結
-
invalidate
方法過程和requestLayout
方法很像,最終都執行了scheduleTraversals()
方法; -
invalidate
方法沒有標記PFLAG_FORCE_LAYOUT
,所以不會執行測量和佈局流程,只是對需要重繪的View進行重繪,也就是隻會調用onDraw方法,不會調用onMeasure和onLayout方法。 -
invalidate
方法只能在UI線程調用,不能在非UI線程調用
postInvalidate
方法
postInvalidate
方法可以在非UI線程調用,其內部在調用了ViewRootImpl的dispatchInvalidateDelayed(View view, long delayMilliseconds)
方法,在此方法中通過Handler,進行線程切換,最終在UI線程中調用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);
}