[英]While loop doesn't work on Android
我需要以 1 秒的延遲顯示數字。 如果沒有 while 循環,它可以工作,但是一旦我添加了 while 循環,它就會在 while 循環結束后打印值。 有人可以在這方面提供幫助。
int state = 0;
int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.b_main);
textView =(TextView) findViewById(R.id.text_main);
listView =(ListView) findViewById(R.id.t_main);
arrayList=new ArrayList<String>();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(state==0){
state=1;
try {
while(count<10) {
textView.setText("Start " + count++);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
state=0;
textView.setText("Stop " + count++);
}
}
});
}
永遠不要在 UI 線程上調用Thread.sleep()
。 您需要將代碼放在一個單獨的線程中,並使用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();
}
不要使用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** )
當您進行與時間相關的操作時,更好的方法是使用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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.