我建了一个小进度条。按下按钮时,进度条开始计数,从1到100。 我在运行时将按钮文本更改为“正在运行”。但是当我试图将文本更改为“再次?”时在它达到100之后(在while循环结束之后),应用程序突然停止 - 每次。 有帮助吗?提前谢谢。
package com.myfirstapplication.owner.myfirstapplication;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextClock;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ProgressBar pg;
Button bt;
int progressStatus = 0;
TextView tv;
Handler handler = new Handler();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pg = (ProgressBar) findViewById(R.id.progressBar);
bt = (Button) findViewById(R.id.btn);
tv = (TextView) findViewById(R.id.textID);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bt.setText("Running.");
progressStatus = 0;
new Thread(new Runnable() {
@Override
public void run() {
while (progressStatus < 100) {
progressStatus++;
handler.post(new Runnable() {
@Override
public void run() {
pg.setProgress(progressStatus);
tv.setText("Progress: " + progressStatus + "/" + pg.getMax());
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
bt.setText("Again?");
}
}).start();
}
});
}
}
答案 0 :(得分:0)
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bt.setText("Running.");
progressStatus = 0;
new Thread(new Runnable() {
@Override
public void run() {
while (progressStatus < 100) {
progressStatus++;
handler.post(new Runnable() {
@Override
public void run() {
pg.setProgress(progressStatus);
tv.setText("Progress: " + progressStatus + "/" + pg.getMax());
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
handler.post(new Runnable() {
@Override
public void run() {
bt.setText("Again?");
}
});
}
}).start();
}
});