单击android中的按钮时,进度条活动无法启动

时间:2013-05-18 15:25:54

标签: android

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

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

当我点击按钮时,进度条无法启动。

1 个答案:

答案 0 :(得分:1)

两件事

  1. 您需要在ProgressDialog实例上调用show,否则将无法显示
  2. progressDialog.incrementProgressBy((INT)(100/20));必须在UI线程上运行,否则您将获得CalledFromWrongTreadException
  3. 要克服第2点,您可以使用HandlerrunOnUiThread