Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在后台对UI进行更改(使用ProgressDialog)?_Java_Android - Fatal编程技术网

Java 在后台对UI进行更改(使用ProgressDialog)?

Java 在后台对UI进行更改(使用ProgressDialog)?,java,android,Java,Android,我正在开发一个应用程序,在其中一个活动中,不同的视图被添加到一个视图组中,这个过程需要一段时间才能启动,所以我想在前台运行一个进度对话框,而UI可以在后台设置 我尝试过的 我试着用 1.AsyncTask但它给出了异常。 2.在使用线程和runnable()时,我得到了InvocationTargetException 我想知道解决这个问题的最佳方法是什么?您不能在后台任务中更改UI 如果使用AsyncTask,则只能通过onPostExecute()或onProgressUpdate()方法更

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

我尝试过的

我试着用

1.AsyncTask但它给出了异常。 2.在使用线程和runnable()时,我得到了InvocationTargetException


我想知道解决这个问题的最佳方法是什么?

您不能在后台任务中更改UI

如果使用
AsyncTask
,则只能通过
onPostExecute()
onProgressUpdate()方法更新UI

另一个选项是使用
处理程序
,它(除其他外)可以在主线程上执行
Runnable
s

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

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

但是您需要知道,您不能从后台线程更改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
  }

}
私有类myAsyncTask扩展了AsyncTask
{
@凌驾
受保护的void onPreExecute()
{
//显示进度对话框
}
@凌驾
受保护的Void doInBackground(Void…arg0)
{
//初始化对象,并对它们进行处理
返回null;
}
@凌驾
受保护的void onPostExecute(void结果)
{
//对UI线程进行更改
//关闭进度对话框
}
}

只需将AsyncTask和更新UI保留在onPostExecute中,而在doInBackground中执行即可。

AsyncTask是一个不错的选择。如果您有错误,您应该修复它们。如果你不喜欢这个粗鲁的回答,你可能想改进你的问题;)AsyncTask不允许在doInBackground()中更改UI它可以工作,但我想在前台显示一个不显示的progressdialog!!我想我们需要更多的信息来解决你的问题。你有你使用的代码的摘录吗?您能告诉我们使用AsyncTask解决方案时出现的异常堆栈吗?使用处理程序它工作正常,但我无法在前台运行ProgressDialog。有什么建议吗?