我将如何在此代码中单独显示每个循环数据,而不是通过循环然后显示数据(我尝试使用计时器但没有工作)。
int noStart = 20;
int minus = 5;
private void waitUntil(long time) {
try {
Thread.sleep(time);
}
catch (InterruptedException e) {
//This is just here to handle an error without crashing
}
}
public void number(View view){
for(int loop = 0;noStart<loop;loop+=5){
noStart -= minus;
TextView tx = (TextView) findViewById(R.id.number);
tx.setText(String.valueOf(noStart));
waitUntil(500);
}
}
答案 0 :(得分:0)
您可以使用处理程序执行此任务。这样你主UI就不会睡觉。
Handler waitHandler = new Handler();
TextView tx = (TextView) findViewById(R.id.number);
waitHandler.post(waitRunnable);
int counter = 0;
static Runnable waitRunnable = new Runnable() {
@Override
public void run() {
for(int i=0; i<5; i++) {
tx.post(new Runnable() {
public void run() {
tx.setText(String.valueOf(counter));
}
});
}
counter+=5;
Thread.sleep(2000);
}
};
这将在tx TextView上设置文本,与5,10,15,20和25之间有2秒的差距。
答案 1 :(得分:0)
如上所述,您可以使用Handler
并设置延迟间隔(以毫秒为单位)。
下面的代码每0.5秒执行5次而不会阻止UI线程。
final Handler h = new Handler();
h.postDelayed(new Runnable() {
private int counter = 0;
public void run() {
// Update your text view here
...
if (++counter < 5) {
h.postDelayed(this, 500);
}
}
}, 500);