Android 2.2:如何使用计时器自动更新文本视图?
我的应用程序中有一些 TextView,我希望每 5 秒自动更新一次。我有一个刷新它们的方法,但是如何制作一个每 5 秒运行该方法的计时器?谢谢!
I have some TextViews in my app that I want updated automatically each 5 seconds. I have a method for refreshing them, but how do I make a timer that runs the method every 5 seconds? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
提供另一种解决方案
Provide another solution
看看扩展 CountDownTimer,它有一个 onFinish() 方法,您可以覆盖以更新您的 TextView,如果您希望重复,请重新启动计时器。如果您只想更新有限次数,也可以绑定到 onTick()。
Look at extending a CountDownTimer, it has an onFinish() method you can overwrite to update your TextView, and restart the timer if you wish to make it repeat. You can also bind to onTick() if you only want to update a finite number of times.
我自己尝试了处理程序解决方案,特别是在阅读资源页面上的这篇文章之后: http://developer.android.com/resources/articles/timed-ui-updates.html。但我希望能够像秒表一样启动和停止计时器,并且在恢复计时器后,处理程序解决方案的更新频率要低得多 - 在模拟器上大约每五秒更新一次。最后,我在博客上找到了一个提示,该提示建议使用扩展 AsyncTask 的内部类的解决方案。您可以使用AsyncTask 中的publishProgress()-onProgressUpdate() 功能。从 onProgressUpdate() 中,您可以在 UI 线程中“直接”进行更改,例如 myTextView.setText(...)。这会更频繁地发布结果。这是该内部类的一个超级简单的实现:
I tried the Handler solution myself, especially after reading this article on the resource pages: http://developer.android.com/resources/articles/timed-ui-updates.html. But I wanted to be able to start and stop the timer much like a stopwatch, and after resuming the timer the Handler solution started updating much less regularly - on the emulator about every five seconds. In the end I found a tip on a blog that suggested the solution with an inner class extending AsyncTask. You can make use of the publishProgress()-onProgressUpdate() functionality in AsyncTask. From onProgressUpdate(), you're allowed to make changes "directly" in your UI thread e.g. myTextView.setText(...). This publishes results much more frequently. Here's a super simple implementation of that inner class: