Android:修改计时器中的 XML 元素
我试图有一个计数器(计算秒和分钟)并每秒在显示屏上更新它。
我的类的 onCreate
中有此代码,它扩展了 Activity
:
timeOnCall = (TextView) findViewById(R.id.time);
minutes = seconds = 0;
timeOnCall.setText(minutes + ":" + seconds);
// Implements the timer
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
++seconds;
if (seconds == 60) {
seconds = 0;
++minutes;
}
// Display the new time
timeOnCall.setText(minutes + ":" + seconds);
}
}, 1000, 1000);
不幸的是,我收到以下错误:
android.view.ViewRoot$CalledFromWrongThreadException: 只有创建视图层次结构的原始
线程
才能触摸其视图。
我不知道如何解决这个问题,因为它已经在 onCreate()
方法中。有谁知道解决方案吗?
I am trying to have a counter (count seconds and minutes) and update it on the display every second.
I have this code in the onCreate
of my class, which extends Activity
:
timeOnCall = (TextView) findViewById(R.id.time);
minutes = seconds = 0;
timeOnCall.setText(minutes + ":" + seconds);
// Implements the timer
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
++seconds;
if (seconds == 60) {
seconds = 0;
++minutes;
}
// Display the new time
timeOnCall.setText(minutes + ":" + seconds);
}
}, 1000, 1000);
Unfortunately, I get the following error:
android.view.ViewRoot$CalledFromWrongThreadException:
Only the original thread
that created a view hierarchy can touch its views.
I am not sure how to fix this as it's already in the onCreate()
method. Does anyone know a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用处理程序来完成此操作,例如:
在 onCreate 中您可以运行:
You can do it with a handler, something lite this:
in onCreate you can then run:
这是因为您试图从不同的线程内部更改文本视图。你不能那样做。您需要将消息发布回拥有文本视图的线程。
这将启动一个与运行 UI 的线程分开的新线程。
编辑:网上有大量您正在寻找的代码的示例。只需谷歌“Android 线程消息处理程序”之类的东西即可。
Its because your trying to change the textview from inside a different thread. You can't do that. You need to post a message back to the thread that owns the textview.
This starts a new thread that is separate from what is running your UI.
Edit: There are tons of examples online for the code you are looking for. Just Google something like "Android thread message handler."
这是您正在尝试执行的操作以及在没有后台线程的情况下执行此操作的完整步骤。这比计时器更可取,因为计时器使用单独的线程来执行更新。
http://developer.android.com/resources/articles/timed-ui -updates.html
Here is a complete step-by-step of what you are trying to do and doing it without a background thread. This is preferred over a timer because a timer uses a separate thread to do the update.
http://developer.android.com/resources/articles/timed-ui-updates.html