Android:requestLayout、invalidate 和 postInvalidate 的区别

提醒:下面源码来自SDK里Android-34版本

一、requestLayout

点击查看requestLayout官网文档

1.1 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.
     *
     * <p>Subclasses which override this method should call the superclass method to
     * handle possible request-during-layout errors correctly.</p>
     * 上面翻译
     * 当某些东西发生改变使。无效时调用这个
     * 这个视图的布局。这将安排视图的布局传递树。
     * 当视图层次结构当前处于布局时,不应该调用这个函数
     * pass ({
   
   @link #isInLayout()})。如果正在进行布局,
     * 请求可能会在结束当前布局传递(然后布局将再次运行)
     * 或在当前绘制框架,并发生下一个布局。
     * 
     * 重写此方法的子类应该调用父类方法正确处理布局期间可能出现的请求错误。
     */
    @CallSuper
    public void requestLayout() {
   
   
        if (isRelayoutTracingEnabled()) {
   
   
            Trace.instantForTrack(TRACE_TAG_APP, "requestLayoutTracing",
                    mTracingStrings.classSimpleName);
            printStackStrace(mTracingStrings.requestLayoutStacktracePrefix);
        }

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

在这里插入图片描述

1.2 requestLayoutDuringLayout方法源码
 /**
     * Called by {
   
   @link android.view.View#requestLayout()} if the view hierarchy is currently
     * undergoing a layout pass. requestLayout(
### 3.1 `postInvalidate()` 与 `invalidate()` 的基本区别Android 中,`invalidate()` `postInvalidate()` 都用于触发 `View` 的重绘操作,但二者适用的线程环境执行机制有所不同。`invalidate()` 只能在主线程(UI 线程)中调用,而 `postInvalidate()` 可以在非 UI 线程中调用,并通过内部机制将刷新请求发送到主线程执行[^1]。 ### 3.2 线程安全性与使用场景 由于 Android 的 UI 操作不是线程安全的,因此所有与 UI 更新相关的操作必须在主线程中完成。`invalidate()` 直接在当前线程执行视图刷新,因此只能在主线程中调用,否则会抛出异常[^2]。而 `postInvalidate()` 内部通过 `Handler` 或 `ViewRootImpl` 的 `mUiHandler` 将刷新请求发布到主线程的消息队列中,从而实现在非 UI 线程安全地更新 UI[^4]。 例如,在子线程中更新 `View` 的典型用法如下: ```java new Thread(new Runnable() { @Override public void run() { // 模拟耗时操作 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } // 在子线程中使用 postInvalidate 刷新 UI view.postInvalidate(); } }).start(); ``` ### 3.3 内部实现机制 尽管 `postInvalidate()` `invalidate()` 最终都会调用到 `invalidateInternal()` 方法来触发 `onDraw()` 的执行,但它们的调用路径不同。`invalidate()` 直接在当前线程执行刷新逻辑,而 `postInvalidate()` 会通过 `ViewRootImpl` 的 `mUiHandler` 向主线程发送刷新消息,确保在主线程中执行 `invalidate()`。 ### 3.4 与 `requestLayout()` 的区别 除了 `invalidate()` `postInvalidate()`,Android 还提供了 `requestLayout()` 方法用于触发视图的重新布局。`requestLayout()` 会触发 `onMeasure()` `onLayout()` 方法,只有在视图的位置或尺寸发生变化时才会触发 `onDraw()`。相比之下,`invalidate()` `postInvalidate()` 仅触发 `onDraw()` 方法[^3]。 ### 3.5 性能与使用建议 由于 `postInvalidate()` 涉及线程切换消息传递,其性能略低于直接在主线程中调用 `invalidate()`。因此,在可以确定操作在主线程中执行时,应优先使用 `invalidate()`。而在子线程中更新 UI 时,应使用 `postInvalidate()` 以避免违反 Android 的单线程 UI 模型。 ### 3.6 总结对比 | 方法 | 所在线程 | 是否触发 `onLayout/onMeasure` | 是否线程安全 | 内部机制 | |------------------|--------------|-------------------------------|---------------|-----------------------------------| | `invalidate()` | 主线程 | 否 | 否 | 直接调用 `invalidateInternal()` | | `postInvalidate()` | 子线程/主线程 | 否 | 是 | 通过 `Handler` 切换到主线程执行 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值