Android 的 invalidate() 和 postInvalidate() 方法有什么区别?
Android 的 invalidate()
和 postInvalidate()
方法有什么区别?每个人什么时候接到电话?这些方法必须只能在扩展 View
的类中调用吗?
What is the difference between Android's invalidate()
and postInvalidate()
methods? When does each one get called? Must the methods be called only in classes which extend View
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你想从 UI 线程重新绘制视图,你可以调用
invalidate()
方法。如果您想从非 UI 线程重新绘制视图,可以调用
postInvalidate()
方法。从
View
类派生的每个类都有 invalidate 和postInvalidate
方法。如果 invalidate 被调用,它会告诉系统当前视图已更改,并且应该尽快重新绘制。由于此方法只能从 UI 线程中调用,因此当您不在 UI 线程中但仍想通知系统您的 View 已更改时,需要使用另一个方法。postInvalidate
方法从非 UI 线程通知系统,并且视图会在 UI 线程上的下一个事件循环中尽快重绘。 SDK 文档中也对此进行了简短的解释:点击此处
更新:
那里从其他线程使用 postInvalidate 时会出现一些问题(例如没有立即更新 UI),这会更有效:
If you want to re-draw your view from the UI thread you can call
invalidate()
method.If you want to re-draw your view from a non-UI thread you can call
postInvalidate()
method.Each class which is derived from the
View
class has the invalidate and thepostInvalidate
method. If invalidate gets called it tells the system that the current view has changed and it should be redrawn as soon as possible. As this method can only be called from your UI thread another method is needed for when you are not in the UI thread and still want to notify the system that your View has been changed. ThepostInvalidate
method notifies the system from a non-UI thread and the view gets redrawn in the next event loop on the UI thread as soon as possible. It is also shortly explained in the SDK documentation:CLICK HERE
UPDATE:
There are some problems that arise when using postInvalidate from other threads (like not having the UI updated right-away), this will be more efficient: