Android:requestLayout、invalidate 和 postInvalidate 的区别

news2024/9/22 19:31:41

提醒:下面源码来自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() should not generally be called during layout,
     * unless the container hierarchy knows what it is doing (i.e., it is fine as long as
     * all children in that container hierarchy are measured and laid out at the end of the layout
     * pass for that container). If requestLayout() is called anyway, we handle it correctly
     * by registering all requesters during a frame as it proceeds. At the end of the frame,
     * we check all of those views to see if any still have pending layout requests, which
     * indicates that they were not correctly handled by their container hierarchy. If that is
     * the case, we clear all such flags in the tree, to remove the buggy flag state that leads
     * to blank containers, and force a second request/measure/layout pass in this frame. If
     * more requestLayout() calls are received during that second layout pass, we post those
     * requests to the next frame to avoid possible infinite loops.
     *
     * <p>The return value from this method indicates whether the request should proceed
     * (if it is a request during the first layout pass) or should be skipped and posted to the
     * next frame (if it is a request during the second layout pass).</p>
     *
     * @param view the view that requested the layout.
     *
     * @return true if request should proceed, false otherwise.
     */
    boolean requestLayoutDuringLayout(final View view) {
        if (view.mParent == null || view.mAttachInfo == null) {
            // Would not normally trigger another layout, so just let it pass through as usual
            return true;
        }
        if (!mLayoutRequesters.contains(view)) {
            mLayoutRequesters.add(view);
        }
        if (!mHandlingLayoutInLayoutRequest) {
            // Let the request proceed normally; it will be processed in a second layout pass
            // if necessary
            return true;
        } else {
            // Don't let the request proceed during the second layout pass.
            // It will post to the next frame instead.
            return false;
        }
    }

注释翻译:
由{@link android.view. view# requestLayout()}调用,如果视图层次是当前的正在进行布局检查。requestLayout()通常 不应该在布局期间调用,
除非容器层次结构知道它在做什么(即,只要
该容器层次结构中的所有子节点都在布局的末尾进行测量和布局
传递该容器)。如果requestLayout()被调用,我们将正确地处理它
通过在帧进行时注册所有请求者。在画面的最后,
我们检查所有这些视图,看看是否还有待处理的布局请求
指示它们没有被其容器层次结构正确处理。如果是这样的话
在这种情况下,我们清除树中所有这样的旗帜,以移除导致的有bug的旗帜状态
空白容器,并强制在此框架中通过第二个请求/测量/布局。如果
在第二次布局过程中接收到更多的requestLayout()调用,我们发布它们
请求转到下一帧,以避免可能的无限循环。

此方法的返回值指示请求是否应该继续
(如果它是第一次布局传递期间的请求)或应该跳过并发布到
下一帧(如果它是第二个布局传递期间的请求)。

查看请求布局的视图。

如果请求应该继续,则返回true,否则返回false。

requestLayoutDuringLayout方法源码-图文分析

在这里插入图片描述

1.3 总结
  • 当视图层次结构当前处于布局时,不应该调用requestLayout方法
  • 会调用measure方法和layout方法

二、invalidate

2.1 invalidate方法源码
 /**
     * Invalidate the whole view. If the view is visible,
     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
     * the future.
     * <p>
     * This must be called from a UI thread. To call from a non-UI thread, call
     * {@link #postInvalidate()}.
     */
    public void invalidate() {
        invalidate(true);
    }

在这里插入图片描述

2.2 invalidate(boolean invalidateCache)方法源码
/**
     * This is where the invalidate() work actually happens. A full invalidate()
     * causes the drawing cache to be invalidated, but this function can be
     * called with invalidateCache set to false to skip that invalidation step
     * for cases that do not need it (for example, a component that remains at
     * the same dimensions with the same content).
     *
     * @param invalidateCache Whether the drawing cache for this view should be
     *            invalidated as well. This is usually true for a full
     *            invalidate, but may be set to false if the View's contents or
     *            dimensions have not changed.
     * @hide
     */
    @UnsupportedAppUsage
    public void invalidate(boolean invalidateCache) {
        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
    }

在这里插入图片描述

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

        if (skipInvalidate()) {
            return;
        }

        // Reset content capture caches
        mPrivateFlags4 &= ~PFLAG4_CONTENT_CAPTURE_IMPORTANCE_MASK;
        mContentCaptureSessionCached = false;

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

在这里插入图片描述

在这里插入图片描述

2.4 isOpaque方法源码
 /**
     * Indicates whether this View is opaque. An opaque View guarantees that it will
     * draw all the pixels overlapping its bounds using a fully opaque color.
     *
     * Subclasses of View should override this method whenever possible to indicate
     * whether an instance is opaque. Opaque Views are treated in a special way by
     * the View hierarchy, possibly allowing it to perform optimizations during
     * invalidate/draw passes.
     *
     * @return True if this View is guaranteed to be fully opaque, false otherwise.
     */
    @ViewDebug.ExportedProperty(category = "drawing")
    public boolean isOpaque() {
        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
                getFinalAlpha() >= 1.0f;
    }

指示此视图是否不透明。一个不透明的视图保证它会这样做
使用完全不透明的颜色绘制与边界重叠的所有像素。

View的子类应该尽可能地覆盖这个方法
实例是否不透明。以一种特殊的方式处理不透明视图
视图层次结构,可能允许它执行优化期间
失效/画传递。

@return True如果这个视图保证是完全不透明的,否则返回false。

2.5 总结
  • 必须在主线程调用invalidate方法
  • invalidate方法会调用onDraw方法绘制新的内容

三、postInvalidate

3.1 postInvalidate方法源码
/**
     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
     * Use this to invalidate the View from a non-UI thread.</p>
     *
     * <p>This method can be invoked from outside of the UI thread
     * only when this View is attached to a window.</p>
     *
     * @see #invalidate()
     * @see #postInvalidateDelayed(long)
     */
    public void postInvalidate() {
        postInvalidateDelayed(0);
    }

在这里插入图片描述

3.2 postInvalidateDelayed方法源码
/**
     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
     *
     * <p>This method can be invoked from outside of the UI thread
     * only when this View is attached to a window.</p>
     *
     * @param left The left coordinate of the rectangle to invalidate.
     * @param top The top coordinate of the rectangle to invalidate.
     * @param right The right coordinate of the rectangle to invalidate.
     * @param bottom The bottom coordinate of the rectangle to invalidate.
     *
     * @see #invalidate(int, int, int, int)
     * @see #invalidate(Rect)
     * @see #postInvalidateDelayed(long, int, int, int, int)
     */
    public void postInvalidate(int left, int top, int right, int bottom) {
        postInvalidateDelayed(0, left, top, right, bottom);
    }
3.3 postInvalidateDelayed(long delayMilliseconds)方法源码
/**
     * <p>Cause an invalidate to happen on a subsequent cycle through the event
     * loop. Waits for the specified amount of time.</p>
     *
     * <p>This method can be invoked from outside of the UI thread
     * only when this View is attached to a window.</p>
     *
     * @param delayMilliseconds the duration in milliseconds to delay the
     *         invalidation by
     *
     * @see #invalidate()
     * @see #postInvalidate()
     */
    public void postInvalidateDelayed(long delayMilliseconds) {
        // We try only with the AttachInfo because there's no point in invalidating
        // if we are not attached to our window
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
        }
    }
3.4 postInvalidateDelayed(long delayMilliseconds, int left, int top, int right, int bottom) 方法源码
/**
     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
     * through the event loop. Waits for the specified amount of time.</p>
     *
     * <p>This method can be invoked from outside of the UI thread
     * only when this View is attached to a window.</p>
     *
     * @param delayMilliseconds the duration in milliseconds to delay the
     *         invalidation by
     * @param left The left coordinate of the rectangle to invalidate.
     * @param top The top coordinate of the rectangle to invalidate.
     * @param right The right coordinate of the rectangle to invalidate.
     * @param bottom The bottom coordinate of the rectangle to invalidate.
     *
     * @see #invalidate(int, int, int, int)
     * @see #invalidate(Rect)
     * @see #postInvalidate(int, int, int, int)
     */
    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
            int right, int bottom) {

        // We try only with the AttachInfo because there's no point in invalidating
        // if we are not attached to our window
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
            info.target = this;
            info.left = left;
            info.top = top;
            info.right = right;
            info.bottom = bottom;

            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
        }
    }

在这里插入图片描述

dispatchInvalidateDelayed方法
在这里插入图片描述

handleMessageImpl方法接收MSG_INVALIDATE消息
在这里插入图片描述

3.5 总结
  • 可以在非UI线程或UI线程中调用postInvalidate
  • 当调用postInvalidate()方法时,会调用dispatchInvalidateDelayed通过Handler将重绘任务添加到主线程的消息队列中。在UI线程的消息循环中,当处理到该消息时,会触发invalidate()方法来进行实际的重绘操作。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1939850.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【C++航海王:追寻罗杰的编程之路】关于空间配置器你知道多少?

目录 1 -> 什么是空间配置器 2 -> 为什么需要空间配置器 3 -> SGI-STL空间配置器的实现原理 3.1 -> 一级空间配置器 3.2 -> 二级空间配置器 3.2.1 -> 内存池 3.2.2 -> SGI-STL中二级空间配置器设计 3.2.3 -> SGI-STL二级空间配置器之空间申请 …

Spring Boot 3.3 【三】Spring Boot RESTful API 增删改查详细教程

Spring Boot RESTful API 增删改查详细教程 一、RESTful 架构风格简介 1. 简介 RESTful API 是一种基于HTTP协议的网络应用接口设计风格&#xff0c;它遵循REST&#xff08;Representational State Transfer&#xff0c;表述性状态转移&#xff09;原则。RESTful架构风格的出…

花几千上万学习Java,真没必要!(二十)

ArrayList 是一种可以动态增长和缩减的数组&#xff0c;与普通的数组相比&#xff0c;它提供了更加灵活的操作方式。ArrayList 内部使用数组来存储元素&#xff0c;但是它会根据需要自动调整数组的大小&#xff0c;以便能够存储更多的元素。 ArrayList 的主要特点包括&#xf…

如何成为学习高手

文章收录在网站&#xff1a;http://hardyfish.top/ 文章收录在网站&#xff1a;http://hardyfish.top/ 文章收录在网站&#xff1a;http://hardyfish.top/ 文章收录在网站&#xff1a;http://hardyfish.top/ 所有的学习方式&#xff0c;核心都是动脑加动手。 区别在于如何让…

吴恩达大模型LLM系列课程学习(更新42门课程)

目录 GPT-4o详细中文注释的Colab中英文字幕观看视频1 浏览器下载插件2 打开官方视频 课程1&#xff1a;Prompt Compression and Query Optimization课程2&#xff1a;Carbon Aware Computing for GenAI developers课程3&#xff1a;Function-calling and data extraction with …

Java语言程序设计——篇六(1)

字符串 概述创建String类对象     字符串基本操作实战演练 字符串查找字符串转换为数组字符串比较实战演练 字符串的拆分与组合 概述 字符串 用一对双引号“”括起来的字符序列。Java语言中&#xff0c;字符串常量或变量均用类实现。 字符串有两大类&#xff1a; 1&…

2024年【起重机司机(限桥式起重机)】考试题及起重机司机(限桥式起重机)新版试题

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 起重机司机(限桥式起重机)考试题参考答案及起重机司机(限桥式起重机)考试试题解析是安全生产模拟考试一点通题库老师及起重机司机(限桥式起重机)操作证已考过的学员汇总&#xff0c;相对有效帮助起重机司机(限桥式起重…

JS 原型与原型链图解:彻底搞懂的终极指南

前言 &#x1f4eb; 大家好&#xff0c;我是南木元元&#xff0c;热爱技术和分享&#xff0c;欢迎大家交流&#xff0c;一起学习进步&#xff01; &#x1f345; 个人主页&#xff1a;南木元元 在JavaScript中&#xff0c;原型和原型链是非常重要的知识点&#xff0c;只有理解了…

Express+mysql单表分页条件查询

声明&#xff08;自己还没测试过&#xff0c;只提供大概逻辑&#xff0c;什么多表连接查询可以在原基础上添加&#xff09; class /*** param connection Express的mysql数据库链接对象* current 当前页* pageSize 一页显示行数* where [{key:id,operator:,value15}], key查询…

【2024最新华为OD-C/D卷试题汇总】[支持在线评测] 卢小姐的生日礼物(200分) - 三语言AC题解(Python/Java/Cpp)

🍭 大家好这里是清隆学长 ,一枚热爱算法的程序员 ✨ 本系列打算持续跟新华为OD-C/D卷的三语言AC题解 💻 ACM银牌🥈| 多次AK大厂笔试 | 编程一对一辅导 👏 感谢大家的订阅➕ 和 喜欢💗 🍿 最新华为OD机试D卷目录,全、新、准,题目覆盖率达 95% 以上,支持题目在线…

pg_restore导入错误的解决思路

背景 开发使用postgresql 数据库&#xff0c;当需要部署时&#xff0c;通过pg_dump导出&#xff0c;通过pg_restore导入&#xff0c;发现导入遇到错误&#xff0c;很多表没有导入。部分报错截图如下&#xff1a; 排查问题 开发中用到了postgresql插件postgis里的地理类型&am…

ORBSLAM3 ORB_SLAM3 Ubuntu20.04 ROS Noetic 虚拟机镜像 下载

下图是build.sh 和 build_ros.sh编译结果截图&#xff1a; slam数据集测试视频&#xff1a; orbslam3 ubuntu20.04 test 下载地址&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1nre0Y9vig5QXIGU52qCLbQ?pwd9rbi 提取码&#xff1a;9rbi

什么是裸机管理程序?

在这个旨在使最终用户体验尽可能无缝的快节奏环境中&#xff0c;企业不断扩展其网络以处理增加的负载&#xff0c;为了应对可扩展性问题并增强其设备的最佳性能&#xff0c;网络管理员开始使用虚拟化技术。 通过使用管理程序虚拟化网络&#xff0c;网络管理员可以实现灵活、可…

C++基础(3.内和对象)

目录 赋值运算符重载: const限制权限&#xff1a; 隐式类型转换&#xff1a; 再探构造函数&#xff1a; static成员&#xff1a; 有元&#xff1a; 内部类&#xff1a; 赋值运算符重载: 赋值运算符重载是一个默认成员函数,用于完成两个已经存在的对象直接的拷贝赋值.要注…

【STM32 HAL库】全双工I2S+双缓冲DMA的使用

1、配置I2S 我们的有效数据是32位的&#xff0c;使用飞利浦格式。 2、配置DMA **这里需要注意&#xff1a;**i2s的DR寄存器是16位的&#xff0c;如果需要发送32位的数据&#xff0c;是需要写两次DR寄存器的&#xff0c;所以DMA的外设数据宽度设置16位&#xff0c;而不是32位。…

pgsql的update语句在set里进行字段的运算 SET sort = sort +1

一、场景 需求&#xff1a;version 版本字段是记录数据更新的次数&#xff0c;新增时自动填充 version1 ,每更新一次数据 version就自增1。项目里单表插入和更新要手写update语句进行插入和更新。 –表中int4类型的字段 version 是1时&#xff0c;由1变成2 – version 是null…

嵌入式人工智能(10-基于树莓派4B的DS1302实时时钟RTC)

1、实时时钟&#xff08;Real Time Clock&#xff09; RTC&#xff0c;全称为实时时钟&#xff08;Real Time Clock&#xff09;&#xff0c;是一种能够提供实时时间信息的电子设备。RTC通常包括一个计时器和一个能够记录日期和时间的电池。它可以独立于主控芯片工作&#xff…

5.过滤器Filter(doFilter()+chain.doFilter())

过滤器Filter 文章目录 过滤器Filter一、过滤器简介1.定义2.作用3.拦截原理4.常用方法:5.Filter的生命周期4.web.xml中配置5.WebFilter 一、过滤器简介 1.定义 过滤器是对Web应用程序的请求和响应添加功能的Web服务组件(实现 javax.servlet.Filter 接口的 Java 类。) 调用web…

Neuralink首款产品Telepathy:意念控制设备的革新与挑战

近年来&#xff0c;科技领域不断涌现出令人惊叹的突破&#xff0c;其中尤以脑机接口&#xff08;BCI&#xff09;技术为代表。近日&#xff0c;Elon Musk的Neuralink公司发布了其首款脑机接口产品Telepathy&#xff0c;引发了广泛关注。本文将详细探讨Telepathy的功能、技术原理…

Java语言程序设计基础篇_编程练习题**15.6(两个消息交替出现)

**15.6(两个消息交替出现) 编写一个程序&#xff0c;当单击鼠标时面板上交替显示两个文本"Java is fun"和"Java is powerful" 代码展示&#xff1a;编程练习题15_6TwoInfo.java package chapter_15;import javafx.application.Application; import javafx…