我必須下載一些圖像並使用圖庫進行顯示。對於我用於圖庫的圖像適配器,我必須使用Async任務開始下載get view方法中的圖像。我的問題是,我不能將下載的圖像視圖返回到調用函數。由於networkonmainthread異常,我不能使用主線程下載。使用異步任務下載圖像並將其顯示在圖庫中
GalleryActivity
public class GalleryActivity extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.gallery);
((Gallery) findViewById(R.id.gallery)).setAdapter(new ImageAdapter(this));
}
圖片適配器
public class ImageAdapter extends BaseAdapter {
public View getView(int position, View convertView, ViewGroup parent) {
new galleryBackground().execute(Integer.toString(position));
ImageView i =null;
return i;
}
}
畫廊
public class galleryBackground extends AsyncTask<String, Integer, String> {
Bitmap bm;
public String[] myRemoteImages = { ....};
ImageView i = new ImageView(GalleryActivity.this);
@Override
protected String doInBackground(String... arg0) {
try {
URL aURL = new URL(myRemoteImages[Integer.parseInt(arg0[0])]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = bitmapFactory.decodeStream(bis);
bis.close();
is.close();
}
@Override
protected void onPostExecute(String result) {
i.setImageBitmap(bm);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new Gallery.LayoutParams(150, 150));
// i have to return this Image view to the calling function
super.onPostExecute(result);
}
謝謝你..現在工作.. :) –