Android View刷新机制

在Android的View刷新机制中,父View负责刷新(invalidateChild)、布局(layoutChild)显示子View。而当子View需要刷新时,则是通知父View刷新子view来完成。

刷新代码如下(mParent为view的父view):
void invalidate(boolean invalidateCache) {
            final AttachInfo ai = mAttachInfo;
            final ViewParent p = mParent;
            //noinspection PointlessBooleanExpression,ConstantConditions
            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
                if (p != null && ai != null && ai.mHardwareAccelerated) {
                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
                    p.invalidateChild(this, null);
                    return;
                }
            }
 
            if (p != null && ai != null) {
                final Rect r = ai.mTmpInvalRect;
                r.set(0, 0, mRight - mLeft, mBottom - mTop);
                // Don't call invalidate -- we don't want to internally scroll
                // our own bounds
                p.invalidateChild(this, r);
            }
        }
    }

invalidate()和postInvalidate() 的区别及使用

当Invalidate()被调用的时候,View的OnDraw()就会被调用;Invalidate()是刷新UI,UI更新必须在主线程,所以invalidate必须在UI线程中被调用,如果在子线程中更新视图的就调用postInvalidate()。

postInvalidate()实际调用的方法,mHandler.sendMessageDelayed,在子线程中用handler发送消息,所以才能在子线程中使用。

    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
        mHandler.sendMessageDelayed(msg, delayMilliseconds);
    }

你可能感兴趣的:(Android View刷新机制)