代码之家  ›  专栏  ›  技术社区  ›  Spredzy

onCreate方法中的AsyncTask和setAdapter

  •  4
  • Spredzy  · 技术社区  · 14 年前

    我正在做一些繁重的网络任务-下载图片(预览)- 为了不阻止我的主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显示所有东西都被下载了,但在我的屏幕上什么都没有。 我尝试在异步任务中执行setAdapter部分,但它告诉我: Only the original thread that created a view hierarchy can touch its views.

    我该怎么办?

    2 回复  |  直到 14 年前
        1
  •  6
  •   kichik    14 年前

    AsyncTask 有一个有用的方法可以实现 onPostExecute() . 任务完成后从原始UI线程调用它。您可以使用它从正确的线程设置适配器。

        2
  •  4
  •   Paresh Mayani jeet    14 年前

    AsyncTask有3个基本方法:

    protected void onPreExecute()
    {
    }
    
    protected void onPostExecute(Void unused)   
    {
      // displaying images
      // set adapter for listview with downloaded items
    }
    
    protected Void doInBackground(Void... params) 
    {
         // downloading and time consuming task 
    }
    

    所以你可以写 g.setAdapter(new ImageAdapter(this)); 在里面 onPostExecute(Void unused) 方法,因为此时,图片已在 doInBackground() 方法。