1:加载图片时,用自定义的图片加载器类,如下:/*** Created by qizepu on 2017/4/15.* 创建一个类 继承AsyncTask 用来加载图片 参数类型是String 返回类型是Bitmap*/public class LoadImageActivity extends AsyncTask<String,Void,Bitmap> {//定义一个图片的接口 用于回调public interface ImageCallBack{void getBitmap(Bitmap bitmap);}//定义变量记住调用者所传递进来的回调监听对象private ImageCallBack imageCallBack;//创建构造方法public LoadImageActivity(ImageCallBack imageCallBack){this.imageCallBack=imageCallBack;}//重写方法@Overrideprotected void onPostExecute(Bitmap bitmap) {super.onPostExecute(bitmap);//设置图片 回调回去if (bitmap != null){imageCallBack.getBitmap(bitmap);}}//加载图片@Overrideprotected Bitmap doInBackground(String... params) {try {String path = params[0];URL url = new URL(path);HttpURLConnection connection = (HttpURLConnection) url.openConnection();//设置请求方式,请求时间及服务器响应时间connection.setRequestMethod("GET");connection.setConnectTimeout(5000);connection.setReadTimeout(5000);//判断服务器是否连接成功并响应if (connection.getResponseCode() == 200){//得到图片流InputStream is = connection.getInputStream();将图片流转化成Bitmap位图,返回Bitmap bitmap = BitmapFactory.decodeStream(is);return bitmap;}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}}2:在适配器类调用自定义图片加载器类的图片,如下:public class MyListViewAdapter extends BaseAdapter {private Context context;private List<Foods.ResultBean.DataBean> list;public MyListViewAdapter(Context context, List<Foods.ResultBean.DataBean> list) {this.context=context;this.list=list;}@Overridepublic int getCount() {return list.size();}@Overridepublic Object getItem(int position) {return null;}@Overridepublic long getItemId(int position) {return 0;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {if (convertView==null){convertView=View.inflate(context, R.layout.listview_item,null);}ImageView image_1 = (ImageView) convertView.findViewById(R.id.image_1);// 使用自定义的AsyTask类
// 将图片的uri作为这个图片一个Tagimage_1.setTag(list.get(position).getAlbums().get(0));
// //设置默认显示的图片image_1.setImageResource(R.mipmap.ic_launcher);设置图片setImage(list.get(position).getAlbums().get(0),image_1);return convertView;}//创建一个方法传两个参数 参数1:图片路径 参数2:imageview控件
//方法里面实例化自定义的加载图片类,实现其接口跟方法public void setImage(final String url, final ImageView imageView){new ImageLoaderAsyncTask(new ImageLoaderAsyncTask.ImageCallBack() {@Overridepublic void callBack(Bitmap bitmap) {//回掉的接口里的方法 判断bitmap不为空 然后判断imageview不为空以及Imageview的Tag是否是设置的Tag//如果是,设置图片if (bitmap != null){if (imageView.getTag() != null && url.equals(imageView.getTag())){imageView.setTag(url);imageView.setImageBitmap(bitmap);}}}}){}.execute(url);}
}