[英]I have an error in a thread making time “run” (update every second)
Here is my code: 这是我的代码:
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
} catch (InterruptedException e) {
}
}
};
thread.start();
The Thread
is called Thread
and I want to display the time in a TextView
called TextView
. Thread
称为Thread
,我想在名为TextView
的TextView
显示时间。 There is some error in the Thread
because even though the time displays in the TextView
, it does not update every second. Thread
存在一些错误,因为即使时间显示在TextView
,它也不是每秒更新一次。 Thanks 谢谢
As stated, you should use Handler
with Runnable
, here is an example with your code: 如前所述,您应该将
Handler
与Runnable
使用,这是代码示例:
final Handler handler = new Handler();
final Runnable task = new Runnable() {
@Override
public void run() {
//Your code
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(task, 1000);
More info about Handlers, in the doc. 有关处理程序的更多信息,请参见文档。
use Runnable
And Handler
使用
Runnable
和Handler
Runnable runnable = new Runnable() {
@Override
public void run() {
Date time = Calendar.getInstance().getTime();
textView.setText(DateFormat.format("hh:mm", time));
handler.postDelayed(this, 1000);
}
};
Handler handler = new Handler();
handler.post(runnable);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.