0

我在单击按钮时调用的方法中编写了以下代码:

final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setProgress(0);  
        progressDialog.setIcon(R.drawable.ic_launcher);
        progressDialog.setTitle("Downloading files…");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setButton(DialogInterface.BUTTON_POSITIVE,"OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,
                int whichButton)
                {
                    Toast.makeText(getBaseContext(),
                            "OK clicked!", Toast.LENGTH_SHORT).show();
                }
        });
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,
                    int whichButton)
                {
                    Toast.makeText(getBaseContext(),
                            "Cancel clicked!", Toast.LENGTH_SHORT).show();
                }
        });
        new Thread(new Runnable(){
            public void run(){
                for (int i=1; i<=20; i++) {
                    try {
                        //---simulate doing something lengthy---
                        Thread.sleep(1000);
                        //---update the dialog---
                        progressDialog.incrementProgressBy((int)(100/20));
                    } catch (InterruptedException e) {                   
                        e.printStackTrace();
                    }
                }
                progressDialog.dismiss();
            }
        }).start();
    }

当我单击按钮时,进度条没有启动。

4

1 回答 1

1

两件事情

  1. 您需要在 ProgressDialog 实例上调用 show 否则它将永远不会显示
  2. progressDialog.incrementProgressBy((int)(100/20)); 必须在 UI 线程上运行,否则你会得到CalledFromWrongTreadException

要克服第 2 点,您可以使用HandlerorrunOnUiThread

于 2013-05-18T15:42:45.083 回答