Android异步加载全解析之使用多线程
异步加载之使用多线程
初次尝试
/** * Using Thread * @param imageView * @param url */ public void showImageByThread(final ImageView imageView, final String url) { mHandler = new Handler() { @Override public void handleMessage(Message msg) { Bitmap bitmap = (Bitmap) msg.obj; imageView.setImageBitmap(bitmap); } }; new Thread() { @Override public void run() { Bitmap bitmap = getBitmapFromUrl(url); Message message = Message.obtain(); message.obj = bitmap; mHandler.sendMessage(message); } }.start(); }
ListView之Recycler机制
public View getView(int position, View convertView, ViewGroup parent)
多线程异步下载正解
/** * Using Thread * @param imageView * @param url */ public void showImageByThread(final ImageView imageView, final String url) { mHandler = new Handler() { @Override public void handleMessage(Message msg) { ImgHolder holder = (ImgHolder) msg.obj; if (holder.imageView.getTag().equals(holder.url)) { holder.imageView.setImageBitmap(holder.bitmap); } } }; new Thread() { @Override public void run() { Bitmap bitmap = getBitmapFromUrl(url); Message message = Message.obtain(); message.obj = new ImgHolder(imageView, bitmap, url); mHandler.sendMessage(message); } }.start(); }
private class ImgHolder { public Bitmap bitmap; public ImageView imageView; public String url; public ImgHolder(ImageView iv, Bitmap bm,String url) { this.imageView = iv; this.bitmap = bm; this.url = url; } }
修改后的方法,依然是使用Handler,这个没有别的选择,首先我们下载图像,然后将图像和ImageView通过一个对象来进行匹配保存。在Handler拿到对象后,通过判断当前的tag与url是否对应来决定是否加载。这里就利用到了我们在Android异步加载全解析之开篇瞎扯淡里面所提到的:
viewHolder.imageView.setTag(url);
这里就派上用场了。
@Override public View getView(int position, View convertView, ViewGroup parent) { String url = mData.get(position); ViewHolder viewHolder = null; if (convertView == null) { viewHolder = new ViewHolder(); convertView = mInflater.inflate(R.layout.listview_item, null); viewHolder.imageView = (ImageView) convertView.findViewById(R.id.iv_lv_item); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.imageView.setTag(url); viewHolder.imageView.setImageResource(R.drawable.ic_launcher); mImageLoader.showImageByThread(viewHolder.imageView, url); return convertView; }
在getView的时候,异步加载图片。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。