[英]I would like to show the timer of a thread in textView (Live)
I have a timer in a thread waiting like 20 seconds before moving to a new activity, what I'm looking for is to show the time whatever decreasing or increasing in a textView in that while. 我在一个线程中有一个计时器,等待大约20秒后再转到新活动,我要寻找的是显示时间,无论那段时间内textView减少还是增加。 here's my code:
这是我的代码:
Thread timer = new Thread() {
public void run() {
try {
sleep(ie);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent i = new Intent(Activity.this, Menu.class);
if (ie == 20000) {
startActivity(i);
overridePendingTransition(R.anim.pushin, R.anim.pushout);
}
}
}
};
timer.start();
thanks for your assisstance 谢谢你的协助
Try a CountDownTimer instead of a Thread: 尝试使用CountDownTimer而不是线程:
CountDownTimer count = new CountDownTimer(20000, 1000)
{
int counter = 20;
@Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
counter--;
textView.setText(String.valueOf(counter));
}
@Override
public void onFinish()
{
startActivity(i);
overridePendingTransition(R.anim.pushin, R.anim.pushout);
}
};
count.start();
Camilo Sacanamboy's answer is the correct one. Camilo Sacanamboy的答案是正确的。 If you want to do this with a Thread, one solution might be like this:
如果要使用线程执行此操作,则一种解决方案可能是这样的:
final TextView status; //Get your textView here
Thread timer = new Thread() {
public void run() {
int time = 20000;
try {
while(time > 0){
time -= 200; //Or whatever you might like
final int currentTime = time;
getActivity().runOnUiThread(new Runnable() { //Don't update Views on the Main Thread
@Override
public void run() {
status.setText("Time remaining: " + currentTime / 1000 + " seconds");
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent i = new Intent(Activity.this, Menu.class);
if (ie == 20000) {
startActivity(i);
overridePendingTransition(R.anim.pushin, R.anim.pushout);
}
}
}
};
timer.start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.