【问题标题】:Dismiss custom dialog from async task从异步任务中关闭自定义对话框
【发布时间】:2017-04-30 17:47:35
【问题描述】:

我什至无法在异步任务本身上创建自定义对话框,所以我调用了一个方法来显示它,这是我的方法:

public void showCustomLocationDialog(String title) {
    final Dialog customDialog = new Dialog(this);
    customDialog.setContentView(R.layout.custom_location_dialog);
    customDialog.setTitle(title);

    if (!customDialog.isShowing()) {
        // set the custom dialog components - title, ProgressBar and button
        TextView text = (TextView) customDialog.findViewById(R.id.textView);
        text.setText(title);
        customDialog.show();
    }else if (customDialog.isShowing())
    {
        customDialog.dismiss();
    }
}

我得到的错误:

java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
....

我在这里所做的是在 onPreExecuteonPostExecute 上调用此方法。

我尝试在 PreExecute 上创建对话框,但是遇到了错误。尤其是“setContentView”。

如何在异步任务完成后关闭我的自定义对话框?

【问题讨论】:

  • AsyncTask 完成时,onPostExecute 函数被调用,所以你应该把你的customDialog.dismiss(); 放进去。

标签: android android-asynctask


【解决方案1】:

Android 不允许更改不是android main thread 的线程中的 gui。在activity.onCreate()view.onClick() atc.. 来自main thread 的android 调用。

问题:你调用 customDialog.dismiss(); 来改变其他线程的 gui

AsyncTask中把你的gui修改只在onPostExecute中,这个方法由主线程调用,一定要从主线程调用AsyncTask.execute(),否则onPostExecute不会调用,

【讨论】:

    【解决方案2】:

    您好,您尝试在 AsyncTast 中的 activity.runOnUiThread 中进行 UI 操作

    onPostExecute{ Activity.runOnUiThread{ Dialog.dismiss() }

    }

    【讨论】:

      猜你喜欢
      • 2014-12-19
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      相关资源
      最近更新 更多