我正在尝试创建一个进度对话框,如下面的代码所示。但问题是,当我点击取消并再次单击进度条(编辑:显示进度条按钮)时,它无法按预期工作。指标移动得更快,有时甚至没有完成就退出。
这是我在屏幕截图上单击“单击以显示...”按钮时调用 onClick3 的代码。
ProgressDialog progressDialogAdvanced;
public void onClick3(View v ){
showDialog(1);
progressDialogAdvanced.setProgress(0);
t = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 1; i <=10; i++){
try{
Thread.sleep(500);
progressDialogAdvanced.incrementProgressBy((int)10);
}catch(InterruptedException e ){
e.printStackTrace();
}
}
progressDialogAdvanced.dismiss();
}
});
t.start();
}
这是创建进度条的代码:
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
progressDialogAdvanced = new ProgressDialog(this);
progressDialogAdvanced.setIcon(R.drawable.ic_launcher);
progressDialogAdvanced.setTitle("Downloading...");
progressDialogAdvanced.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialogAdvanced.setButton(DialogInterface.BUTTON_POSITIVE,"OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//To change body of implemented methods use File | Settings | File Templates.
//progressDialogAdvanced.setProgress(0);
Toast.makeText(getBaseContext(),"OkClicked",Toast.LENGTH_SHORT).show();
}
});
progressDialogAdvanced.setButton(DialogInterface.BUTTON_NEGATIVE,"Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
progressDialogAdvanced.dismiss();
Toast.makeText(getBaseContext(),"Cancelled",Toast.LENGTH_SHORT).show();
}
});
return progressDialogAdvanced;
}
}
编辑:
使用取消()而不是解雇()。使用如下所示的处理程序仍然没有解决任何问题。我必须等到线程被破坏。
for(int i = 1; i <=10; i++){
try{
Thread.sleep(500);
}catch(InterruptedException e ){
e.printStackTrace();
}
progressBarHandler.post(new Runnable() {
public void run() {
progressDialogAdvanced.incrementProgressBy(10);
}
});
}
progressDialogAdvanced.cancel();