我第一次尝试使用Async对象时出现的问题 .
我有一个主要活动,其中一些TextViews已经以编程方式创建并添加到LinearLayout . 还有一个按钮,当单击它时,实例化AsyncTask对象并在doInBackGround方法中获得结果 . 应该如何将结果字符串传输到TextViews?
a)通过从onPostExecute方法调用这些TextViews的SetText方法,b)在主要活动中使用意图和onActivityResult方法c)一些其他方式(线索会很好!)
谢谢!
我会选择 AsyncTask 选项 . 我'm guessing that as you already have one in place, the obtaining results part that happens when you click the button takes time, so it'的好设计在 AsyncTask 的 doInBackground 方法中有 .
AsyncTask
doInBackground
然后你可以在 AsyncTask 的 onPostExecute 方法中调用每个 TextView 的 setText(...) 方法 . 或者,它更合适,您可以在后台计算期间使用 publishProgress(...) 和 onProgressUpdate(...) 方法(请参阅AsyncTask documentation)获取结果时更新每个视图,而不必等到结束 .
onPostExecute
TextView
setText(...)
publishProgress(...)
onProgressUpdate(...)
请记住,您只能从 onPreExecute , onProgressUpdate 和 onPostExecute 方法调用 setText(...) ,因为(至少从您的解释看起来这样)视图已在UI线程上创建,因此它们只能从相同的方法修改线程,这些方法运行 .
onPreExecute
onProgressUpdate
使用AsyncTask时,可以使用 doInBackground 方法进行处理,使用 onPostExecute 更新任何UI更改 . 所以,如果你需要使用 AsyncTask ,我会去 option A .
将TextViews设为私有并在doInBackground中定义它们,然后你可以在onPostExecute中调用setText方法或者在doInBackground中调用最后一个东西,但我建议使用onPostExecute .
3 回答
我会选择
AsyncTask
选项 . 我'm guessing that as you already have one in place, the obtaining results part that happens when you click the button takes time, so it'的好设计在AsyncTask
的doInBackground
方法中有 .然后你可以在
AsyncTask
的onPostExecute
方法中调用每个TextView
的setText(...)
方法 . 或者,它更合适,您可以在后台计算期间使用publishProgress(...)
和onProgressUpdate(...)
方法(请参阅AsyncTask documentation)获取结果时更新每个视图,而不必等到结束 .请记住,您只能从
onPreExecute
,onProgressUpdate
和onPostExecute
方法调用setText(...)
,因为(至少从您的解释看起来这样)视图已在UI线程上创建,因此它们只能从相同的方法修改线程,这些方法运行 .使用AsyncTask时,可以使用
doInBackground
方法进行处理,使用onPostExecute
更新任何UI更改 . 所以,如果你需要使用AsyncTask
,我会去 option A .将TextViews设为私有并在doInBackground中定义它们,然后你可以在onPostExecute中调用setText方法或者在doInBackground中调用最后一个东西,但我建议使用onPostExecute .