【问题标题】:Android doesn't show ProgressDialogAndroid 不显示 ProgressDialog
【发布时间】:2012-12-29 14:50:03
【问题描述】:

我试图在加载 Activity 时显示 ProgressDialog,但它没有显示出来。

这里是Activity调用的方法onCreate

  private void loadBuilding(String[] b) {

        ProgressDialog pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMax(6);

        pd.setTitle(R.string.loading);

        pd.show();

        LoadBuilding lb = new LoadBuilding();
        lb.initialize(this,  pd);

        lb.execute(b);

        try {
              lb.get();
        } catch (Exception e) {
              e.printStackTrace();
        } 

        pd.dismiss();

        if (building == null) 
              showError();
  }

LoadBuilding 是一个 AsyncTask,我在其中加载建筑物并设置进度。

谢谢大家。

【问题讨论】:

  • 尝试从代码中删除pd.dismiss() 及其后面的所有行,并将其放入异步任务的 onPostExecute 方法中。我认为您的对话框实际上已显示,但很快关闭。

标签: android android-asynctask android-progressbar


【解决方案1】:

问题是 progressDialog.dismiss() 必须在:

  • 代码中显示的try/catch的catch
  • AsyncTask 的 onPostExecute 方法。

另外我使用的测试数据太少,所以它起起落落太快了。

【讨论】:

    【解决方案2】:

    使用 AsyncTask 进行后台处理和在前台更新进度。我认为这最适合您的任务。

    private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }
    
     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }
    
     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
    }
    

    尝试在 try and catch 块中添加你的 progressDismiss()

    try
     {
       pg.dismiss();
      }
    Catch()
    {
     }
    

    【讨论】:

      猜你喜欢
      • 2012-04-06
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 2012-07-20
      • 2012-08-13
      • 1970-01-01
      相关资源
      最近更新 更多