4

我正在做一些繁重的網絡任務 - 下載圖片(預覽) - 對於我的主UI不被阻止它做了一個AsyncTask,我想把它們放在一個GridView中,但我設置了AsyncTask完成之前的適配器。有些代碼會更有益AsyncTask和setAdapter的onCreate方法

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的顯示,一切都被dowloaded但我的屏幕上也沒有。 我嘗試在我的AsyncTask中執行setAdapter部分,但它告訴我:Only the original thread that created a view hierarchy can touch its views.

我該怎麼辦?

回答

6

AsyncTask有一個有用的方法可以實現名爲onPostExecute()。它在任務完成後從原始UI線程調用。您可以使用它從正確的線程設置適配器。

4

的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()方法內。

0

爲了方便異步下載圖像,並將其設置爲視圖可以使用非常有益的和簡單的庫畢加索:

Picasso.with(context) 
    .load(url) 
    .placeholder(R.drawable.user_placeholder) 
    .error(R.drawable.user_placeholder_error) 
    .into(imageView); 

如果您使用的是Android Studio和gradle這個只需添加這對應用級gradle這個文件:

compile 'com.squareup.picasso:picasso:2.5.2' 

最新版本可在Github