3 回答
TA贡献1812条经验 获得超5个赞
永远不要调用Thread.sleep()UI 线程。您需要将代码放在一个单独的线程中,并使用runOnUiThread以下方法发布结果:
if(state==0){
state=1;
new Thread(new Runnable() {
@Override
public void run() {
try {
while(count<10) {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText("Start " + count++);
}
});
Thread.sleep(1000);
count++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
TA贡献1796条经验 获得超10个赞
不要使用Thread.sleep(). 使用处理程序来强制执行您想要的延迟。
final Handler handler = new Handler();
final int delay1 = 1000; // adjust as needed
handler.postDelayed(new Runnable() {
public void run() {
// Code Block 1. Code here will be executed after 1000 millisec
}
}, delay1);
// Code Block 2. Code here will be executed immediatelly ( before **Code Block 1** )
TA贡献1780条经验 获得超4个赞
当您进行与时间相关的操作时,更好的方法是使用CountDownTimer. Thread.sleep()在主线程上使用是不好的,因为当线程休眠时你的 Ui 会卡住
这是一个关于如何实现它的示例 CountDownTimer
int state = 0, count = 0;
TextView textView;
CountDownTimer timer;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
button=(Button)findViewById(R.id.b_main);
textView =(TextView) findViewById(R.id.text_main);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (state == 0) {
state = 1;
startTimer();
} else {
state = 0;
if (timer != null) {
timer.cancel();
}
textView.setText("Stop " + count++);
}
}
});
}
public void startTimer() {
timer = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
count++;
textView.setText("Start " + count);
}
@Override
public void onFinish() {
//10 sec finished
}
};
timer.start();
}
添加回答
举报