我正在开发progressBar。我的项目的想法是用户能够用一个按钮开始/恢复progressBar的进展,并在需要时用另一个按钮(如秒表)重置它。 在阅读了一些关于如何使用线程处理其视觉进展的主题之后,我想知道我是否以正确的方式进行,如果我的代码可以改进。我想正确地中断或恢复线程。谢谢你的帮助。
这是我的主要活动:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progbar_horiz);
pbar = (ProgressBar) findViewById(R.id.progress_bar_horiz);
textField = (TextView) findViewById(R.id.texttime);
startButton = (Button) findViewById(R.id.button_ring_Start);
stopButton = (Button) findViewById(R.id.button_ring_Stop);
Drawable draw = getResources().getDrawable(R.drawable.custom_progress_bar);
pbar.setProgressDrawable(draw);
maxBar = pbar.getMax();
startButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(startButton.getText() == "Start") {
pbar.setProgress(0);
progress = 0;
startButton.setText("Pause");
myThread = new ProgressThread();
myThread.start();
} else {
if (startButton.getText() == "Pause") {
startButton.setText("Resume");
myThread.interrupt();
} else {
startButton.setText("Pause");
myThread = null;
myThread = new ProgressThread();
myThread.start();
}
}
}
});
stopButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(myThread != null) {
myThread.interrupt();
pbar.setProgress(0);
progress = 0;
startButton.setText("Start");
}
}
});
}
private class ProgressThread extends Thread {
@Override
public void run() {
while (!this.isInterrupted() && progress < maxBar) {
try { Thread.sleep(DELAY_MS);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
progress += 1;
handler.post(new Runnable() {
public void run() {
pbar.setProgress(progress);
if (progress == maxBar) {
startButton.setText("Start");
}
}
});
}
}
}
}