いくつかの画像をダウンロードして、Gallery を使用して表示する必要があります。ギャラリーに使用している画像アダプターの場合、非同期タスクを使用して get view メソッドで画像のダウンロードを開始する必要があります。私の問題は、ダウンロードした画像ビューを呼び出し元の関数に返せないことです。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);
}