我必须下载一些图像并使用图库显示它们。对于我用于画廊的图像适配器,我必须开始使用异步任务在获取视图方法中下载图像。我的问题是我无法将下载的图像视图返回给调用函数。由于networkonmainthread异常,我无法使用主线程下载。
图库活动
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);
}