[android]代码库
public class ImageListAdapter extends BaseAdapter {
private Context context;
private String[] myImages = null;
public ImageListAdapter (Context context, String[] myImages) {
this.context = context;
this.myImages = myImages;
}
@Override
public int getCount() {
if (myImages == null) {
return 0;
}
return myImages.length;
}
@Override
public String getItem (int position) {
if (position < 0 || myImages == null || position > myImages.length) {
return null;
}
return myImages[position];
}
@Override
public long getItemId (int position) {
return position;
}
@Override
public View getView (int position, View convertView, ViewGroup parent) {
View item = null;
if (convertView != null) {
item = convertView;
} else {
item = View.inflate (context, R.layout.image_item, null);
}
final ImageView imageView = (ImageView) item.findViewById (R.id.image);
final String image = getItem (position);
if (image == null) {
return item;
}
//对每个图片地址创建一个线程,
new Thread() {
public void run() {
Message msg = new Message();
msg.what = 0;
//getBitmap省略了,就是从网上通过http下载图片,转化成一个Bitmap
Bitmap bitmap = getBitmap (image);
List list = new ArrayList();
list.add (bitmap);
list.add (imageView);
msg.obj = list;
handler.sendMessage (msg);
}
} .start();
return item;
}
private Handler handler = new Handler() {
@Override
public void handleMessage (Message msg) {
switch (msg.what) {
case 0://接到从线程内传来的图片bitmap和imageView.
//这里只是将bitmap传到imageView中就行了。只所以不在线程中做是考虑到线程的安全性。
List list = (List) msg.obj;
Bitmap bitmap = (Bitmap) list.get (0);
ImageView iv = (ImageView) list.get (1);
iv.setImageBitmap (bitmap);
break;
default:
super.handleMessage (msg);
}
}
};
}