invalidate和requestLayout经常被用来刷新界面,有的时候2个一起用,TextView的源码里也经常看到2者一起用的情况。什么时候该用哪个呢?为什么有的时候2个要一起用呢?
本文所从源码是6.0.1来研究下2者的原理和区别以及如何使用。测试工程InvalidateDemo
Invalidate
PFLAG_DRAWING_CACHE_VALID、PFLAG_INVALIDATED
这里我们要注意view的2个flag,一个是PFLAG_INVALIDATED,一个是PFLAG_DRAWING_CACHE_VALID。
/**
* Indicates that this view was specifically invalidated, not just dirtied because some
* child view was invalidated. The flag is used to determine when we need to recreate
* a view's display list (as opposed to just returning a reference to its existing
* display list).
*
* @hide
*/
static final int PFLAG_INVALIDATED = 0x80000000;
看起来好像,子view invalidate就会导致父view PFLAG_INVALIDATED,但是我实际试了下,子view invalidate只会导致子view PFLAG_INVALIDATED,父view的PFLAG_INVALIDATED不会被设置。
而PFLAG_DRAWING_CACHE_VALID代表drawing_cache有效了,这个才是其中某个子view invalidate了,一个子view invalidate会导致父view的PFLAG_DRAWING_CACHE_VALID被置0,父view的父view也会PFLAG_DRAWING_CACHE_VALID被置为0,后文会分析。
Invalidate具体分析
先来看看invalidate方法,这是view的一个方法,一般我们想更新某个view会调用此方法.我们都知道view的invalidate会导致这个view被重新绘制,这个是怎么实现的呢?
我们知道invalidate会导致ViewRootImpl的peformDraw被调用,那怎么保证不绘制所有的view,而只绘制某个view呢?大概流程图如下所示
step1.invalidateInternal
大概流程如上面的图所展示的,View的invalidate会调到invalidateInternal,里面会在L7设置2个标志位PFLAG_INVALIDATED和PFLAG_DRAWING_CACHE_VALID,PFLAG_INVALIDATED置为1,PFLAG_DRAWING_CACHE_VALID置为0. 并且调用invalidateChild(L17)。代码如下。
void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
boolean fullInvalidate) {
。。。。
mPrivateFlags |= PFLAG_DIRTY;
//invalidateCache一般为true
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();
}
}
}
step2.invalidateChildInParent
invalidateChild内部有个dowhile循环,不停调用父view的invalidateChildInParent,一直到调用ViewRootImpl的invalidateChildInParent。我们看invalidateChild的L21,把PFLAG_DRAWING_CACHE_VALID置为0,在dowhile循环后,当前view的所有父view,父view的父view。。。都会被PFLAG_DRAWING_CACHE_VALID置为0.调用invalidateChildInParent会传进去一个Rect叫dirty,代表子窗口需要刷新的rect,父窗口会根据这个rect和父窗口本身做union,从而得到父窗口需要刷新的rect区域,然后再传给父窗口的父窗口,一直递归直到ViewRootImpl
public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
if ((mPrivateFlags & PFLAG_DRAWN) == PFLAG_DRAWN ||
(mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) {
if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) !=
FLAG_OPTIMIZE_INVALIDATE) {
dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX,
location[CHILD_TOP_INDEX] - mScrollY);
if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0) {
dirty.union(0, 0, mRight - mLeft, mBottom - mTop);
}
final int left = mLeft;
final int top = mTop;
if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
if (!dirty.intersect(0, 0, mRight - left, mBottom - top)) {
dirty.setEmpty();
}
}
//此处抹掉PFLAG_DRAWING_CACHE_VALID
mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
location[CHILD_LEFT_INDEX] = left;
location[CHILD_TOP_INDEX] = top;
if (mLayerType != LAYER_TYPE_NONE) {
mPrivateFlags |= PFLAG_INVALIDATED;
}
return mParent;
} else {
...
}
}
return null;
}
而ViewRootImpl的invalidateChildInParent内部调用而invalidateRectOnScreen进而调用scheduleTraversals。
step3. scheduleTraversals
scheduleTraversals一般都会调用performDraw进而调draw,在draw内,如果发现mDirty非空就会调mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
这是ThreadedRenderer内的方法了,里面会调updateRootDisplayList进而调updateViewTreeDisplayList。
private void updateViewTreeDisplayList(View view) {
view.mPrivateFlags |= View.PFLAG_DRAWN;
view.mRecreateDisplayList = (view.mPrivateFlags & View.PFLAG_INVALIDATED)
== View.PFLAG_INVALIDATED;
view.mPrivateFlags &= ~View.PFLAG_INVALIDATED;
view.updateDisplayListIfDirty();
view.mRecreateDisplayList = false;
}
此时view是DecorView,DecorView会往下分发找到需要重绘的view,然后调用此view的draw方法。假设调用invalidate的view为a,a的parent为ap。我们知道此时a的PFLAG_DRAWING_CACHE_VALID 为0,PFLAG_INVALIDATED为1.而a的父族view,ap,app,appp等的PFLAG_DRAWING_CACHE_VALID为0,PFLAG_INVALIDATED为0.
所以上边会把mRecreateDisplayList设置为false,后面会知道mRecreateDisplayList代表了哪个view要被重绘,只有a的mRecreateDisplayList为true,其他都是false。
来看DecorView如何分发的。DecorView的updateViewTreeDisplayList会调updateDisplayListIfDirty,如下,因为DecorView是a的父族view,所以会进L10的if,然后mRecreateDisplayList为false,所以会进L16.在L19调用dispatchGetDisplayList,哦哟,看到分发的影子了。
/**
* Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
* @hide
*/
@NonNull
public RenderNode updateDisplayListIfDirty() {
final RenderNode renderNode = mRenderNode;
。。。
if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
|| !renderNode.isValid()
|| (mRecreateDisplayList)) {
// Don't need to recreate the display list, just need to tell our
// children to restore/recreate theirs
if (renderNode.isValid()
&& !mRecreateDisplayList) {
mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
mPrivateFlags &= ~PFLAG_DIRTY_MASK;
dispatchGetDisplayList();
return renderNode; // no work needed
}
// If we got here, we're recreating it. Mark it as such to ensure that
// we copy in child display lists into ours in drawChild()
mRecreateDisplayList = true;
int width = mRight - mLeft;
int height = mBottom - mTop;
int layerType = getLayerType();
final DisplayListCanvas canvas = renderNode.start(width, height);
canvas.setHighContrastText(mAttachInfo.mHighContrastText);
try {
// Fast path for layouts with no backgrounds
if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
dispatchDraw(canvas);
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().draw(canvas);
}
} else {
draw(canvas);
}
}
} finally {
renderNode.end(canvas);
setDisplayListProperties(renderNode);
}
} else {
mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
mPrivateFlags &= ~PFLAG_DIRTY_MASK;
}
return renderNode;
}
dispatchGetDisplayList的代码很简单,主要就是L4的for循环,内调用recreateChildDisplayList,让子view recreate display。
protected void dispatchGetDisplayList() {
final int count = mChildrenCount;
final View[] children = mChildren;
for (int i = 0; i < count; i++) {
final View child = children[i];
if (((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null)) {
recreateChildDisplayList(child);
}
}
if (mOverlay != null) {
View overlayView = mOverlay.getOverlayView();
recreateChildDisplayList(overlayView);
}
if (mDisappearingChildren != null) {
final ArrayList disappearingChildren = mDisappearingChildren;
final int disappearingCount = disappearingChildren.size();
for (int i = 0; i < disappearingCount; ++i) {
final View child = disappearingChildren.get(i);
recreateChildDisplayList(child);
}
}
}
再看recreateChildDisplayList,内部给mRecreateDisplayList赋值,然后调用updateDisplayListIfDirty(咦回去了,只是此时对象变成了DecorView的child),好了,分发在这里完全成型了。
private void recreateChildDisplayList(View child) {
child.mRecreateDisplayList = (child.mPrivateFlags & PFLAG_INVALIDATED) != 0;
child.mPrivateFlags &= ~PFLAG_INVALIDATED;
child.updateDisplayListIfDirty();
child.mRecreateDisplayList = false;
}
总结
parent:updateDisplayListIfDirty-》dispatchGetDisplayList-》for() recreateChildDisplayList
child:recreateChildDisplayList-》updateDisplayListIfDirty
我们在具体分析下各个view会如何表现,核心代码是updateDisplayListIfDirty,
父族view的执行流程是
parent:updateDisplayListIfDirty-》dispatchGetDisplayList-》for() recreateChildDisplayList
child:recreateChildDisplayList-》updateDisplayListIfDirty
如果是a本身,那么L10进去,但是由于a的mRecreateDisplayList为true,所以会到L43进行重绘,这就是invalidate导致的分发过程
如果不是父族view也不是a本身,那么PFLAG_DRAWING_CACHE_VALID为1,会走L10的else设置标志位,然后结束,不会分发到子view。
所以整个过程中只有a调用了draw方法进行重绘,这是PFLAG_INVALIDATED标志位起的作用。
/**
* Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
* @hide
*/
@NonNull
public RenderNode updateDisplayListIfDirty() {
final RenderNode renderNode = mRenderNode;
。。。
if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
|| !renderNode.isValid()
|| (mRecreateDisplayList)) {
// Don't need to recreate the display list, just need to tell our
// children to restore/recreate theirs
if (renderNode.isValid()
&& !mRecreateDisplayList) {
mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
mPrivateFlags &= ~PFLAG_DIRTY_MASK;
dispatchGetDisplayList();
return renderNode; // no work needed
}
// If we got here, we're recreating it. Mark it as such to ensure that
// we copy in child display lists into ours in drawChild()
mRecreateDisplayList = true;
int width = mRight - mLeft;
int height = mBottom - mTop;
int layerType = getLayerType();
final DisplayListCanvas canvas = renderNode.start(width, height);
canvas.setHighContrastText(mAttachInfo.mHighContrastText);
try {
// Fast path for layouts with no backgrounds
if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
dispatchDraw(canvas);
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().draw(canvas);
}
} else {
draw(canvas);
}
}
} finally {
renderNode.end(canvas);
setDisplayListProperties(renderNode);
}
} else {
mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
mPrivateFlags &= ~PFLAG_DIRTY_MASK;
}
return renderNode;
}
问题onMeasure、onLayout
还有个问题,invalidate会不会导致onMeasure和onLayout被调用呢??
在performTraversals方法中,mLayoutRequested为false,所有onMeasure和onLayout都不会被调用。
ViewGroup的invalidate
我们再来看看ViewGroup的invalidate,刚才说了invalidate如果是个view,那就只有自己本身会draw,如果是ViewGroup呢?
因为一般的ViewGroup都是SKIP_DRAW的,所以会走到L38 dispatchDraw, dispatchDraw的实现一般在ViewGroup里,就是调用子view的draw(注意是调用的3参的draw方法,而不是单参的方法)
所以一般来说ViewGroup的invalidate就是对子view进行重绘(android.view.View#draw(android.graphics.Canvas, android.view.ViewGroup, long))
总结
1、view的invalidate并不会调用ViewRootImpl的invalidate。
2、performDraw的过程中,大部分view的 updateDisplayListIfDirty都会被调用,但是只有设了标志位的view会调用draw方法进而调用onDraw
requestLayout
主体过程
读完了invalidate再看requestLayout就很简单了,
1.view的requestLayout会调用parent的requestLayout,直到ViewRootImpl的requestLayout。ViewRootImpl的requestLayout代码如下
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
可以看到mLayoutRequested变true了,然后触发了scheduleTraversals
2.我们可以简单的认为mLayoutRequested为true会触发perfomMeasure(内部会调用onMeasure)和performLayout(内部会调用onLayout)。然后在performDraw内部draw的过程中发现mDirty为空,所以onDraw不会被调用,不重绘。
这么看来requestLayout不会导致onDraw调用了?
也不见得,我们知道requestLayout会导致perfomMeasure和performLayout,如果在layout过程中发现l,t,r,b和以前不一样,那就会触发一次invalidate。代码在View的setFrame中,这个会在layout时被调用。
protected boolean setFrame(int left, int top, int right, int bottom) {
boolean changed = false;
if (DBG) {
Log.d("View", this + " View.setFrame(" + left + "," + top + ","
+ right + "," + bottom + ")");
}
if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
changed = true;
// Remember our drawn bit
int drawn = mPrivateFlags & PFLAG_DRAWN;
int oldWidth = mRight - mLeft;
int oldHeight = mBottom - mTop;
int newWidth = right - left;
int newHeight = bottom - top;
boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
// Invalidate our old position
invalidate(sizeChanged);
mLeft = left;
mTop = top;
mRight = right;
mBottom = bottom;
mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
。。。
}
所以requestLayout有可能会导致onDraw被调用,也可能不导致onDraw被调用,取决于view的l,t,r,b是否改变
part or full
requestLayout会导致整个view tree的measure/layout吗?
我们在说invalidate的时候,invalidate会对调用的view进行标记,到时候只要重绘标记了PFLAG_INVALIDATED的view就可以了。但是requestLayout的过程中,我们没有看到对requestLayout的标记(本以为是mViewRequestingLayout,结果没卵用)。那么一个a调用requestLayout和ap调用requestLayout效果一样吗?
答案是不一样,但是有时候效果也一样。
看看下边requestLayout的代码,其实主要就是L16,L17设置了PFLAG_FORCE_LAYOUT和PFLAG_INVALIDATED 2个标志位,特别是PFLAG_FORCE_LAYOUT。
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;
}
}
一个view调用了requestLayout,那么他自己与他的父族view都会被设置为PFLAG_FORCE_LAYOUT,我们在看看measure过程,要进入L18,measure的核心代码处必须满足3个条件之一,而他自己与他的父族view都会被设置为PFLAG_FORCE_LAYOUT,所以他们都必然会被重新measure,但是其他的view就不一定了,就看这3个条件是否会满足。
结论是requestLayout会导致部分view重新measure和layout。a的requestLayout必然会导致a,ap...的重新measure,ap的requestLayout必定会导致ap的measure,但不一定会导致a的measure
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
boolean optical = isLayoutModeOptical(this);
if (optical != isLayoutModeOptical(mParent)) {
Insets insets = getOpticalInsets();
int oWidth = insets.left + insets.right;
int oHeight = insets.top + insets.bottom;
widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth);
heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
}
// Suppress sign extension for the low bytes
long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
widthMeasureSpec != mOldWidthMeasureSpec ||
heightMeasureSpec != mOldHeightMeasureSpec) {
//....measure核心代码
}
mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
}
mOldWidthMeasureSpec = widthMeasureSpec;
mOldHeightMeasureSpec = heightMeasureSpec;
mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
(long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
}
onMeasure和onLayout的关系
一般来说我们认为调用了onMeasure就会调用onLayout,onMeasure和onLayout是强相关的,为什么这么认为呢?看下边代码
measure的代码简化后,如下所示,在满足3条件时,进入主measure流程,调用onMeasure,然后设置PFLAG_LAYOUT_REQUIRED,看标志就明白了,打上了这个标志,就表示此view需要layout。
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
widthMeasureSpec != mOldWidthMeasureSpec ||
heightMeasureSpec != mOldHeightMeasureSpec) {
...
onMeasure(widthMeasureSpec, heightMeasureSpec);
mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
}
}
再看layout内怎么用上此标志位的,如果changed或者PFLAG_LAYOUT_REQUIRED,那就调用onLayout,这个flag就是刚才我们onMeasure完毕后设置上的,所以可以认为调用了onMeasure就会调用onLayout
public void layout(int l, int t, int r, int b) {
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;
。。。
}
mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}
总结
1.view不停找parent可以一直找到DecorView,按理说DecorView是顶点了,但是DecorView还有个虚拟父view,ViewRootImpl。 ViewRootImpl不是一个View或者ViewGroup,他有个成员mView是DecorView,所有的操作从ViewRootImpl开始自上而下分发
2.view的invalidate不会导致ViewRootImpl的invalidate被调用,而是递归调用父view的invalidateChildInParent,直到ViewRootImpl的invalidateChildInParent,然后触发peformTraversals,会导致当前view被重绘,由于mLayoutRequested为false,不会导致onMeasure和onLayout被调用,而OnDraw会被调用
3.一个view的invalidate会导致本身PFLAG_INVALIDATED置1,导致本身以及父族viewgroup的PFLAG_DRAWING_CACHE_VALID置0
4.requestLayout会直接递归调用父窗口的requestLayout,直到ViewRootImpl,然后触发peformTraversals,由于mLayoutRequested为true,会导致onMeasure和onLayout被调用。不一定会触发OnDraw
5.requestLayout触发onDraw可能是因为在在layout过程中发现l,t,r,b和以前不一样,那就会触发一次invalidate,所以触发了onDraw,也可能是因为别的原因导致mDirty非空(比如在跑动画)
- requestLayout会导致自己以及父族view的PFLAG_FORCE_LAYOUT和PFLAG_INVALIDATED标志被设置。
7.一般来说,只要刷新的时候就调用invalidate,需要重新measure就调用requestLayout,后面再跟个invalidate(为了保证重绘),这是我个人的理解。
参考文献
aosp6.0.1
http://zjmdp.github.io/2012/07/04/invalidate-in-Android/