Android 的 invalidate() 和 postInvalidate() 方法有什么区别?

发布于 2024-12-07 08:12:29 字数 132 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

平生欢 2024-12-14 08:12:29

如果你想从 UI 线程重新绘制视图,你可以调用 invalidate() 方法。

如果您想从非 UI 线程重新绘制视图,可以调用 postInvalidate() 方法。

View 类派生的每个类都有 invalidate 和 postInvalidate 方法。如果 invalidate 被调用,它会告诉系统当前视图已更改,并且应该尽快重新绘制。由于此方法只能从 UI 线程中调用,因此当您不在 UI 线程中但仍想通知系统您的 View 已更改时,需要使用另一个方法。 postInvalidate 方法从非 UI 线程通知系统,并且视图会在 UI 线程上的下一个事件循环中尽快重绘。 SDK 文档中也对此进行了简短的解释:

点击此处

更新:

那里从其他线程使用 postInvalidate 时会出现一些问题(例如没有立即更新 UI),这会更有效:

runOnUiThread(new Runnable() {
    public void run() {
    myImageView.setImageBitmap(image);
    imageView.invalidate();
    }
});

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 the postInvalidate 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. The postInvalidate 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:

runOnUiThread(new Runnable() {
    public void run() {
    myImageView.setImageBitmap(image);
    imageView.invalidate();
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文