onCreate 方法中的 AsyncTask 和 setAdapter
我正在做一些繁重的网络任务 - 下载图片(预览) - 为了不阻止我的主 UI,它在 AsyncTask 中执行了此操作,我想将它们放入 GridView 中,但我在 AsyncTask 完成之前设置了适配器。一些代码会更有帮助
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
new LoadAllPictures().execute();
GridView g = (GridView) findViewById(R.id.gridview);
g.setAdapter(new ImageAdapter(this));
}
所以最后 Logcat 显示所有内容都已下载,但我的屏幕上什么也没有。 我尝试在 AsyncTask 中执行 setAdapter 部分,但它告诉我:只有创建视图层次结构的原始线程才能触摸其视图。
我应该做什么?
I am doing some heavy network tasks - downloading pictures (previews) -
For my main UI to not be blocked it did that in an AsyncTask, I want to put them in a GridView but I set the adapter before the AsyncTask finishes. Some code will be more helpfull
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
new LoadAllPictures().execute();
GridView g = (GridView) findViewById(R.id.gridview);
g.setAdapter(new ImageAdapter(this));
}
So at the end the Logcat shows that everything had been dowloaded but nothing on my screen.
I tried doing the setAdapter part in my AsyncTask but it tells me that: Only the original thread that created a view hierarchy can touch its views.
What should I do ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
AsyncTask
有一个有用的方法,您可以实现名为onPostExecute()
。任务完成后从原始 UI 线程调用它。您可以使用它从正确的线程设置适配器。AsyncTask
has a useful method you can implement namedonPostExecute()
. It's called from the original UI thread after the task has completed. You can use it to set the adapter from the correct thread.AsyncTask有3个基本方法:
所以可以在
onPostExecute(Voidused)
方法里面写g.setAdapter(new ImageAdapter(this));
,因为此时图片已在doInBackground()
方法中下载。AsyncTask has 3 basic methods:
so you can write
g.setAdapter(new ImageAdapter(this));
inside theonPostExecute(Void unused)
method because at this time, the pictures are already downloaded inside thedoInBackground()
method.