【问题标题】:How to change progressDialog text如何更改进度对话框文本
【发布时间】:2018-06-25 12:47:42
【问题描述】:

我有一个 asynctask 但如果我实现 Thread.Sleep ,那么我的应用程序崩溃了,我不知道为什么,在 onPreExecute 我可以看到我的第一条消息,然后在两秒后它出现了我放入 doInBackground 的另一条消息,但是它不工作

private class sendMail extends AsyncTask<Void, Void, Void> {


        protected void onPreExecute() {
            dialog.setMessage("Please wait...");
            dialog.show();

        }

        // automatically done on worker thread (separate from UI thread)
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            dialog.setMessage("Downloading files...");

            new BackgroundTask().execute();

//MY DOWNLOADING METHODS STUFF

然后我在其他地方关闭此对话框

日志

执行doInBackground()时出错

【问题讨论】:

    标签: java android android-asynctask progressdialog


    【解决方案1】:

    您无法从后台线程访问 UI 元素,您可以在 onProgressUpdate 中更新进度条,最重要的是您需要在 doInBackground 中 publishProgress(value) 并使用 onProgressUpdate 进行更新。阅读有关 AsyncTask 的更多信息here

    示例代码:

    class MyTask extends AsyncTask<Integer, Integer, String> {
            @Override
            protected String doInBackground(Integer... params) {
                for (; count <= params[0]; count++) {
                    try {
                        Thread.sleep(1000);
                        publishProgress(count);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return "Task Completed.";
            }
            @Override
            protected void onPostExecute(String result) {
                progressBar.setVisibility(View.GONE);
                    txt.setText(result);
                    btn.setText("Restart");
            }
            @Override
            protected void onPreExecute() {
                txt.setText("Task Starting...");
            }
            @Override
            protected void onProgressUpdate(Integer... values) {
                txt.setText("Running..."+ values[0]);
                progressBar.setMessage("Downloading files...");
                progressBar.setProgress(values[0]);
            }
        }
    

    【讨论】:

    • 老兄,这是一个进度条,我正在使用进度对话框,还请参考您粘贴该代码的位置,因为我已经看到该教程页面
    • 老兄,两者都是 UI 元素,是的,我从网上复制了代码以向您展示示例,除非有更详细的信息我无法在此处解释,否则不需要提供链接.如果你能正确阅读我的答案,你会找到答案,我也可以看到其他人也回答了同样的问题。我建议您阅读有关“从 AsyncTask 访问 UI 元素”的内容,并请注意在 Activity 中以图形方式显示的任何内容都是护理 UI 元素,包括只能从 UI 线程访问的进度对话框。我真的想帮助你而不是别的。
    【解决方案2】:

    使用 UI 线程在 doInBackground 中显示对话框消息参考此https://stackoverflow.com/a/15757788/6626966

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-18
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多