在doINBackground中设置textview android

问题描述:

我有一个主类A,从中我创建一个对象到类B扩展Asynctask。在B的doInBackground设置内容视图A.现在,我要更新的TextView的,但它给在doINBackground中设置textview android

Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

例外。我试图在B中声明setcontentview,但没有用,请问谁能告诉如何编辑A中的Textview?

+0

尝试在AsyncTask的onPostExecute函数中执行此操作。 – Triode 2013-04-26 06:46:48

你需要调用setText()从UI线程,所以无论是从onPreExecute()onPostExecute()onProgressUpdate()

你也可以在doInBackground()使用runOnUiThread()处理程序,但那种失败的使用的AsyncTask的目的。

+0

但是,我更新这个textview作为进度条更新时,所以只需要在后台做! – bharath 2013-04-26 07:53:05

+1

@bharath然后使用'publishProgress()'将信息传递给'onProgressUpdate()'并从那里上传它。 – 2013-04-26 07:54:29

+0

但我不能通过发布通过数字,它需要无效na? – bharath 2013-04-26 08:09:22

我们不应该在doinBackgroud中执行任何UI更改。你应该并且可以在后期执行中执行。也可以在preexecute或onProgressUpdate中设置通知。

希望这会帮助你。

doInBackground是工作线程。你已经在UI线程中处理了View。请在onPreExecute()onPostExecute()onProgressUpdate。所有这些都在UI线程中工作。

当然你可以将Integer传递给onProgressUpdate。请注意第二paramters:AysncTask<Void, Integer, VOid>,第二个参数是指onProgressUpdate参数类型

+0

谢谢,但在进度更新,它只接受空白,我需要传递一个整数值,这是可能的吗? – bharath 2013-04-26 08:07:00

如果文本更新与进步的信息做,那么你可以使用该publishProgress()/onProgressUpdate()

如果它不是更广泛的进展更新,那么我与拉格哈夫 - 你应该考虑另一种方法。

重写onProgressUpdate并在doInBackground中调用publishProgress