在后台更改UI工作(使用ProgressDialog)?

时间:2013-02-13 09:33:03

标签: java android

我正在开发一个应用程序,其中一个活动将不同的视图添加到ViewGroup中,此过程需要一段时间启动,所以我想在前台运行进度对话框,而UI可以在后台设置。

我尝试过什么

我尝试使用

1. AsyncTask 但它提供了例外。 2.使用线程和 runnable()时,我收到 InvocationTargetException

我想知道最好的方法是什么?

3 个答案:

答案 0 :(得分:1)

您无法从后台任务进行UI更改。

如果您使用AsyncTask,则只能使用onPostExecute()onProgressUpdate()方法更新用户界面。

另一种选择是使用Handler,其中(以及其他)可以在主线程上执行Runnable

编辑: Handler必须在主线程上实例化。在任何主题中,您都可以使用post(Runnable)sendMessage(Message)及其各种变体。对于sendMessage(),您需要覆盖handleMessage(Message)

答案 1 :(得分:0)

你能插入一些代码吗?这将有助于确定问题的原因。

但是你需要知道你不能从后台线程更改UI。它会给你一个例外。 您可以做的是编写AsyncTask,它初始化对象并在其doInBackground方法中为它们赋值,然后在其onPostExecute方法中修改UI线程。

它看起来像这样:

private class myAsyncTask extends AsyncTask<Void,Void,Void>
{
  @Override
  protected void onPreExecute()
  {
   //show progress dialog
  }

  @Override
  protected Void doInBackground(Void... arg0)
  {
    //init objects, and do stuff with them
    return null;
  }

  @Override
  protected void onPostExecute(Void result)
  {
    //make changes to UI thread 
    //close progress dialog
  }

}

答案 2 :(得分:0)

Juste保留您的AsyncTask并在onPostExecute中更新UI,而不是在doInBackground中执行。