/**
* @param url 本地或网络的url
* @return url的bitmap
*/
public static Bitmap getLocalOrNetBitmap(String url)
{
Bitmap bitmap = BitmapFactory.decodeResource(sContext.getResources(), R.drawable.store_item_default);
if (url != null) {
InputStream in = null;
BufferedOutputStream out = null;
try
{
//读取图片输入流
in = new BufferedInputStream(new URL(url).openStream(), 2 * 1024);
//准备输出流
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 2 * 1024);
byte[] b = new byte[1024];
int read;
//将输入流变为输出流
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
out.flush();
//将输出流转换为bitmap
byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
data = null;
return bitmap;
}
catch (IOException e)
{
e.printStackTrace();
return bitmap;
}
}
return bitmap;
}
异步获取,保证不阻塞主线程
private void asyncloadImage(final ImageView imageView, final String uri) {
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
Bitmap bitmap = (Bitmap) msg.obj;
if (imageView != null && uri != null) {
imageView.setImageBitmap(bitmap);
}
}
}
};
// 子线程,开启子线程去下载或者去缓存目录找图片,并且返回图片在缓存目录的地址
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
//这个URI是图片下载到本地后的缓存目录中的URI
if (uri != null ) {
Bitmap bitmap = getLocalOrNetBitmap(uri);
Message msg = new Message();
msg.what = 1;
msg.obj = bitmap;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
}
在adapter中的getview
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mission_itemview, null);
holder = new ViewHolder();
/**得到各个控件的对象*/
holder.icon = (ImageView) convertView.findViewById(R.id.mission_pre_img);
convertView.setTag(holder); //绑定ViewHolder对象
}
else {
holder = (ViewHolder) convertView.getTag(); //取出ViewHolder对象
}
/**设置TextView显示的内容,即我们存放在动态数组中的数据*/
asyncloadImage(holder.icon, mList.get(position).mAdvdefInfo3.mIcon);
return convertView;
}