进度对话框显示但没有进度条显示且消息未更新

Progress Dialog Shows but no Progress Bar Shows and Message Isn't Updating

我有一个从片段调用的 class。进度更新被调用,但消息不会更新。我也没有看到任何进度条或微调器。只是标题和消息,看到了一些类似的问题,但进度条根本没有显示。此外,我的消息在 onProgressUpdate 中根本不会更新,但打印出的值确实表明它在 onProgressUpdate 内部递增。

编辑:这是我开始任务的方式

DownloadFilesTask download = new DownloadFilesTask();
download.execute(urls.toArray(new String[urls.size()]));

这是class

private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {

ProgressDialog progressDialog;

@Override
protected void onPreExecute()
{
    progressDialog = ProgressDialog.show(getActivity(), "Downloading","Downloaded 0/"+urls.size(), false);
    progressDialog.setProgress(0);
    progressDialog.setMax(urls.size());
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}

@Override
protected Long doInBackground(String[] urls) {
    int count = urls.length;
    long totalSize = 0;
    for (int i = 0; i < count; i++) {
            //Do things in background here
            publishProgress(new Integer[] {i});
    }
    return totalSize;
}

@Override
protected void onProgressUpdate(final Integer... progress) {
    System.out.println(progress[0]); //This does print correctly
    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            progressDialog.setProgress(progress[0]);
            progressDialog.setMessage("Downloaded "+ progress[0] +"/"+urls.size());
        }
    });
}

@Override
protected void onPostExecute(Long result) {
    progressDialog.dismiss();
    Toast t = Toast.makeText(getActivity(), "Downloaded", Toast.LENGTH_LONG);
    t.show();
}

}

不确定确切原因,但不需要在 runnablesetProgress,因为 onProgressUpdate 将在 UI 线程上 运行。

尝试更换

getActivity().runOnUiThread(new Runnable() { @Override public void run() { progressDialog.setProgress(progress[0]); progressDialog.setMessage("Downloaded "+ progress[0] +"/"+urls.size()); } });

progressDialog.setProgress(progress[0]); progressDialog.setMessage("Downloaded "+ progress[0] +"/"+urls.size());

另外 - 你在 doInbackground() 做网络工作吗,否则我们看不到进展 onPostExecute()

问题出在 ProgressDialog 的初始化方式上。

将您的 onPreExecute 替换为:

@Override
protected void onPreExecute() {
    progressDialog = new ProgressDialog(activity);
    progressDialog.setTitle("Downloading");
    progressDialog.setMessage("Downloaded 0/" + urls.size());
    progressDialog.setIndeterminate(false);
    progressDialog.setProgress(0);
    progressDialog.setMax(urls.size());
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.show();
}

本质上,您需要在调用 show 之前调用 setProgressStyle

此外,您可以删除 onProgressUpdate 中的 runOnUiThread 代码,因为 onProgressUpdate 是在 UI 线程上调用的。