【问题标题】:Dismissing dialog inside Asynctask triggered IllegalArgumentException关闭 Asynctask 中的对话框触发了 IllegalArgumentException
【发布时间】:2014-06-04 03:52:47
【问题描述】:

我一直在使用对话框来显示Asynctask 进度。通过这样做,我在onPreExecute 中对其进行了初始化,并在onPostExecute 中将其关闭。我不确定当我设置一个仅在它不为 null 并且它正在显示但仍触发 IllegalArgumentException: View not attached to window manager

时才关闭的条件时出了什么问题

代码如下:

  public class SampleTask extends AsyncTask<String, Void, String> {
        public ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(SampleActivity.this);
            pDialog.setMessage(getString(R.string.loading));
            pDialog.setCancelable(false);
            pDialog.show();
        }
        @Override
        protected String doInBackground(String... path) {
            .
            .
            .
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(null);
            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }
            .
            .
            .
        }
    }

我阅读了here 类似的解决方案,但如果我将null != pDialog &amp;&amp; pDialog.isShowing() 放在相同条件下会有所不同吗?

【问题讨论】:

  • 我认为代码是写的
  • 删除 super.onPostExecute(null);
  • 您旋转手机了吗?如果是,请尝试为该活动处理 configChanges。也试试这个protected void onCancelled() {if (null != pDialog &amp;&amp; pDialog.isShowing()) { pDialog.dismiss(); } };
  • 这通常发生在 configChanges 或 Activity 在调用 ProgressDialog.dismiss() 之前完成/销毁时

标签: android android-asynctask android-dialog illegalargumentexception


【解决方案1】:

您的问题是您只接受主 UI 线程中的 android 视图。 Read this link for more detail 所以当你在onPostExecute(String) 中调用pDialog.dismiss(); 时,它会在另一个线程上运行,所以android 会抛出新的IllegalArgumentException。我为您提供了一些解决方案,希望对您有所帮助:
1.我一直用这个解决方案,但一点都不好:

Handler handler = new Handler();
Runnable runable = new Runnable() {
    @Override
    public void run() {
        // TODO something you would like to do with Android UI.
    }
};
handler.post(runable);

处理程序将创建一个新线程以在 UI 线程上运行,以便您可以使用 Android UI。
2. 有时我尝试使用interface。它比上面的解决方案更有效,当然,它使我花费更多的精力。

【讨论】:

  • 实际上Asynctask 本身在另一个线程中,所以基本上,在我的主 UI 线程中将对话框放置在其中是不同的。
  • 那么,我的解决方案能帮到你吗?
猜你喜欢
  • 2014-11-05
  • 1970-01-01
  • 2018-08-08
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多