0

我正在尝试创建一个进度对话框,如下面的代码所示。但问题是,当我点击取消并再次单击进度条(编辑:显示进度条按钮)时,它无法按预期工作。指标移动得更快,有时甚至没有完成就退出。

这是我在屏幕截图上单击“单击以显示...”按钮时调用 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;
  }
}

从 0 到 100 显示 100% 正确的指示器

编辑:

使用取消()而不是解雇()。使用如下所示的处理程序仍然没有解决任何问题。我必须等到线程被破坏。

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();
4

1 回答 1

0

您需要添加进度的最大大小,例如:

progressBar.setMax(100);

看这个例子:http ://www.mkyong.com/android/android-progress-bar-example/

于 2013-09-03T22:01:21.717 回答