【问题标题】:AsyncTask and setAdapter in onCreate methodsonCreate 方法中的 AsyncTask 和 setAdapter
【发布时间】:2010-11-11 12:20:23
【问题描述】:

我正在做一些繁重的网络任务——下载图片(预览)—— 为了不阻止我的主 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 部分,但它告诉我:Only the original thread that created a view hierarchy can touch its views.

我该怎么办?

【问题讨论】:

    标签: android android-asynctask android-sdk-2.1 android-gridview


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      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 
      }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多