• 使用image-loader异步加载图片


    1. 主类-获得图片的地址

    关键点:

    1>.良好的代码风格:

        init();

        getdata();

        setadapter();

    2>loader = new AsyncLoader(context);

    package com.example.androidtest;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    import com.nostra13.universalimageloader.core.ImageLoader;
    import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
    
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.view.Window;
    import android.widget.AdapterView;
    import android.widget.BaseAdapter;
    import android.widget.Button;
    import android.widget.GridView;
    import android.widget.ImageButton;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.ListView;
    import android.widget.RelativeLayout;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.widget.AdapterView.OnItemClickListener;
    
    /**
     * 应用
     * 
     * @author tf
     * 
     */
    public class AscTaskActivity extends Activity {
    
    	private GridView picgrid;
    	private List<Map<String, String>> list;
    	private HashMap<String, String> map;
    	
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    		setContentView(R.layout.activity_pic_list);
    
    		initView();
    		getData();
    		VideoListAdapter adapter = new VideoListAdapter(this, list);
    		picgrid.setAdapter(adapter);
    	}
    
    	private void getData() {
    		list = new ArrayList<Map<String, String>>();
    		for (int i = 0; i < 10; i++) {
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("pic_adress", "http://192.168.1.107:8080/MobileSafeServer/pic1.png");
    		
    			list.add(map);
    		}
    		
    	}
    	
    	private void initView() {
    		picgrid = (GridView) findViewById(R.id.picgrid);
    	}
    
    
    
    	class VideoListAdapter extends BaseAdapter {
    		private AsyncLoader loader;
    		private Context context;
    		private List<Map<String, String>> data;
    		private LayoutInflater inflater;
    
    		public VideoListAdapter(Context context, List<Map<String, String>> list) {
    			this.context = context;
    			this.data = list;
    			inflater = LayoutInflater.from(context);
    			loader = new AsyncLoader(context);
    			
    		}
    
    		@Override
    		public int getCount() {
    			// TODO Auto-generated method stub
    			return data.size();
    		}
    
    		@Override
    		public Object getItem(int position) {
    			// TODO Auto-generated method stub
    			return data.get(position);
    		}
    
    		@Override
    		public long getItemId(int position) {
    			// TODO Auto-generated method stub
    			return position;
    		}
    
    		
    		@SuppressLint("ResourceAsColor")
    		@Override
    		public View getView(final int position, View convertView,
    				ViewGroup parent) {
    			final ViewHolder holder;
    			if (null == convertView) {
    				convertView = inflater.inflate(R.layout.pic_grid_item, null);
    				holder = new ViewHolder();
    				holder.pic_iamge_icon = (ImageView) convertView
    						.findViewById(R.id.pic_iamge_icon);
    
    				convertView.setTag(holder);
    
    			} else {
    				holder = (ViewHolder) convertView.getTag();
    			}
    		   //   holder.pic_iamge_icon.setText(data.get(position).get("pic_adress"));
    			
    			loader.displayImage(data.get(position).get("pic_adress"),
    					
    					holder.pic_iamge_icon);
    		return convertView;
    		}
    
    		// 视图容器类,属性对应布局文件元素
    		private class ViewHolder {
                ImageView pic_iamge_icon;
              //  TextView pic_iamge_icon;
    		}
    
    	}
    }
    

    2.AsyncLoader

    关键点:

    imageLoader.init(ImageLoaderConfiguration.createDefault(context));

    public void displayImage(String uri, ImageView imageView) {
    imageLoader.init(ImageLoaderConfiguration.createDefault(context));
    imageLoader.displayImage(uri, new ImageViewAware(imageView, false),
    options);
    }

    package com.example.androidtest;
    
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.widget.ImageView;
    
    import com.nostra13.universalimageloader.core.DisplayImageOptions;
    import com.nostra13.universalimageloader.core.ImageLoader;
    import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
    import com.nostra13.universalimageloader.core.assist.ImageScaleType;
    import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
    import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
    
    public class AsyncLoader {
    
    	private DisplayImageOptions options;
    	private ImageLoader imageLoader;
    	private Context context;
    
    	public AsyncLoader(Context context) {
    		super();
    		this.context = context;
    		options = new DisplayImageOptions.Builder()
    				.showImageOnLoading(R.drawable.default_image) // 璁剧疆鍥剧墖鍦ㄤ笅杞芥湡闂存樉绀虹殑鍥剧墖
    				.showImageForEmptyUri(R.drawable.default_image)// 璁剧疆鍥剧墖Uri涓虹┖鎴栨槸閿欒�鐨勬椂鍊欐樉绀虹殑鍥剧墖
    				.showImageOnFail(R.drawable.default_image) // 璁剧疆鍥剧墖鍔犺浇/瑙g爜杩囩▼涓�敊璇�椂鍊欐樉绀虹殑鍥剧墖
    				.cacheInMemory(true)// 璁剧疆涓嬭浇鐨勫浘鐗囨槸鍚︾紦瀛樺湪鍐呭瓨涓?				.cacheOnDisk(true)// 璁剧疆涓嬭浇鐨勫浘鐗囨槸鍚︾紦瀛樺湪SD鍗′腑
    				// .considerExifParams(true) //鏄�惁鑰冭檻JPEG鍥惧儚EXIF鍙傛暟锛堟棆杞�紝缈昏浆锛?				// .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//璁剧疆鍥剧墖浠ュ�浣曠殑缂栫爜鏂瑰紡鏄剧ず
    				.bitmapConfig(Bitmap.Config.RGB_565)// 璁剧疆鍥剧墖鐨勮В鐮佺被鍨?/
    				// .delayBeforeLoading(int delayInMillis)//int
    				// delayInMillis涓轰綘璁剧疆鐨勪笅杞藉墠鐨勫欢杩熸椂闂?				// 璁剧疆鍥剧墖鍔犲叆缂撳瓨鍓嶏紝瀵筨itmap杩涜�璁剧疆
    				// .preProcessor(BitmapProcessor preProcessor)
    				.resetViewBeforeLoading(false)// 璁剧疆鍥剧墖鍦ㄤ笅杞藉墠鏄�惁閲嶇疆锛屽�浣?				.imageScaleType(ImageScaleType.EXACTLY)
    
    				.build();// 鏋勫缓瀹屾垚
    		imageLoader = ImageLoader.getInstance();
    		// type =new PreferencesHelper(context,
    		// Constant.PRE_SETTING_FILE).getValueInt(Constant.PRE_SETTING_IMAGE_KEY);
    		// netWorkType =AndroidUtil.getNetWorkType(context);
    	}
    
    	public AsyncLoader(Context context, int resId) {
    		super();
    		this.context = context;
    		options = new DisplayImageOptions.Builder().showImageOnLoading(resId) // 璁剧疆鍥剧墖鍦ㄤ笅杞芥湡闂存樉绀虹殑鍥剧墖
    				.showImageForEmptyUri(resId)// 璁剧疆鍥剧墖Uri涓虹┖鎴栨槸閿欒�鐨勬椂鍊欐樉绀虹殑鍥剧墖
    				.showImageOnFail(resId) // 璁剧疆鍥剧墖鍔犺浇/瑙g爜杩囩▼涓�敊璇�椂鍊欐樉绀虹殑鍥剧墖
    				.cacheInMemory(true)// 璁剧疆涓嬭浇鐨勫浘鐗囨槸鍚︾紦瀛樺湪鍐呭瓨涓?				.cacheOnDisk(true)// 璁剧疆涓嬭浇鐨勫浘鐗囨槸鍚︾紦瀛樺湪SD鍗′腑
    				// .considerExifParams(true) //鏄�惁鑰冭檻JPEG鍥惧儚EXIF鍙傛暟锛堟棆杞�紝缈昏浆锛?				// .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//璁剧疆鍥剧墖浠ュ�浣曠殑缂栫爜鏂瑰紡鏄剧ず
    				.bitmapConfig(Bitmap.Config.RGB_565)// 璁剧疆鍥剧墖鐨勮В鐮佺被鍨?/
    				// .delayBeforeLoading(int delayInMillis)//int
    				// delayInMillis涓轰綘璁剧疆鐨勪笅杞藉墠鐨勫欢杩熸椂闂?				// 璁剧疆鍥剧墖鍔犲叆缂撳瓨鍓嶏紝瀵筨itmap杩涜�璁剧疆
    				// .preProcessor(BitmapProcessor preProcessor)
    				.resetViewBeforeLoading(false)// 璁剧疆鍥剧墖鍦ㄤ笅杞藉墠鏄�惁閲嶇疆锛屽�浣?				.imageScaleType(ImageScaleType.EXACTLY)
    
    				.build();// 鏋勫缓瀹屾垚
    
    		imageLoader = ImageLoader.getInstance();
    	}
    
    	public void displayImage(String uri, ImageView imageView) {
    		imageLoader.init(ImageLoaderConfiguration.createDefault(context));
    		imageLoader.displayImage(uri, new ImageViewAware(imageView, false),
    				options);
    	}
    
    	public void displayImageWithUri(String uri, ImageView imageView) {
    		imageLoader.displayImage(uri, new ImageViewAware(imageView, false),
    				options);
    	}
    
    	public void displayImage(String uri, ImageView imageView,
    			ImageLoadingListener listener) {
    		
    	
    		imageLoader.displayImage(uri, new ImageViewAware(imageView, false),
    				options, listener);
    	}
    
    	public void displayImageBG(String uri, ImageView imageView) {
    		imageLoader.displayImage(uri, new BgImageAware(imageView), options);
    	}
    
    	public void displayImageWithFile(String path, ImageView imageView) {
    		imageLoader.displayImage("file://" + path, imageView);
    	}
    
    	/*
    	 * public void displayImageAuto(String uri, ImageView imageView) {
    	 * imageLoader
    	 * .displayImage(GlobalApplication.getInstance().getBaseUrl()+getNetTypeURi
    	 * ()+uri, new ImageViewAware(imageView,false), options, new
    	 * ImageLoadingListener() {
    	 * 
    	 * @Override public void onLoadingStarted(String arg0, View arg1) { // TODO
    	 * Auto-generated method stub
    	 * 
    	 * }
    	 * 
    	 * @Override public void onLoadingFailed(String arg0, View arg1, FailReason
    	 * arg2) { // TODO Auto-generated method stub
    	 * 
    	 * }
    	 * 
    	 * @Override public void onLoadingComplete(String arg0, View view, Bitmap
    	 * loadedImage) { if(loadedImage!=null){ UIUtils.setAutoLayout(context,
    	 * view, loadedImage); } }
    	 * 
    	 * @Override public void onLoadingCancelled(String arg0, View arg1) { //
    	 * TODO Auto-generated method stub
    	 * 
    	 * } }); }
    	 */
    
    }
    

    3.BgImageAware.java

    关键点:

    记住要导包:image-loader.jar

    和添加权限

    <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

    package com.example.androidtest;
    
    import java.lang.ref.Reference;
    import java.lang.ref.WeakReference;
    
    import android.annotation.SuppressLint;
    import android.graphics.Bitmap;
    import android.graphics.drawable.BitmapDrawable;
    import android.graphics.drawable.Drawable;
    import android.os.Build;
    import android.os.Looper;
    import android.view.View;
    import android.view.ViewGroup;
    
    import com.nostra13.universalimageloader.core.assist.ViewScaleType;
    import com.nostra13.universalimageloader.core.imageaware.ImageAware;
    import com.nostra13.universalimageloader.utils.L;
    
    @SuppressLint("NewApi")
    public class BgImageAware implements ImageAware {
    
    	public static final String WARN_CANT_SET_DRAWABLE = "Can't set a drawable into view. You should call ImageLoader on UI thread for it.";
    	public static final String WARN_CANT_SET_BITMAP = "Can't set a bitmap into view. You should call ImageLoader on UI thread for it.";
    
    	protected Reference<View> viewRef;
    	protected boolean checkActualViewSize;
    
    	public BgImageAware(View view) {
    		this(view, true);
    	}
    
    	public BgImageAware(View view, boolean checkActualViewSize) {
    		this.viewRef = new WeakReference<View>(view);
    		this.checkActualViewSize = checkActualViewSize;
    	}
    
    	@Override
    	public int getWidth() {
    		View view = viewRef.get();
    		if (view != null) {
    			final ViewGroup.LayoutParams params = view.getLayoutParams();
    			int width = 0;
    			if (checkActualViewSize && params != null
    					&& params.width != ViewGroup.LayoutParams.WRAP_CONTENT) {
    				width = view.getWidth(); // Get actual image width
    			}
    			if (width <= 0 && params != null)
    				width = params.width; // Get layout width parameter
    			return width;
    		}
    		return 0;
    	}
    
    	@Override
    	public int getHeight() {
    		View view = viewRef.get();
    		if (view != null) {
    			final ViewGroup.LayoutParams params = view.getLayoutParams();
    			int height = 0;
    			if (checkActualViewSize && params != null
    					&& params.height != ViewGroup.LayoutParams.WRAP_CONTENT) {
    				height = view.getHeight(); // Get actual image height
    			}
    			if (height <= 0 && params != null)
    				height = params.height; // Get layout height parameter
    			return height;
    		}
    		return 0;
    	}
    
    	@Override
    	public ViewScaleType getScaleType() {
    		return ViewScaleType.CROP;
    	}
    
    	@Override
    	public View getWrappedView() {
    		return viewRef.get();
    	}
    
    	@Override
    	public boolean isCollected() {
    		return viewRef.get() == null;
    	}
    
    	@Override
    	public int getId() {
    		View view = viewRef.get();
    		return view == null ? super.hashCode() : view.hashCode();
    	}
    
    	@Override
    	public boolean setImageDrawable(Drawable drawable) {
    		if (Looper.myLooper() == Looper.getMainLooper()) {
    			View view = viewRef.get();
    			if (view != null) {
    				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    					view.setBackground(drawable);
    				} else {
    					view.setBackgroundDrawable(drawable);
    				}
    				return true;
    			}
    		} else {
    			L.w(WARN_CANT_SET_DRAWABLE);
    		}
    		return false;
    	}
    
    	@Override
    	public boolean setImageBitmap(Bitmap bitmap) {
    		if (Looper.myLooper() == Looper.getMainLooper()) {
    			View view = viewRef.get();
    			if (view != null) {
    				Drawable drawable = bitmap == null ? null : new BitmapDrawable(
    						view.getResources(), bitmap);
    				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    					view.setBackground(drawable);
    				} else {
    					view.setBackgroundDrawable(drawable);
    				}
    				return true;
    			}
    		} else {
    			L.w(WARN_CANT_SET_BITMAP);
    		}
    		return false;
    	}
    }
    
  • 相关阅读:
    alpha冲刺9
    alpha冲刺8
    alpha冲刺7
    alpha冲刺6
    团队作业——随堂小测(同学录)
    alpha冲刺5
    alpha冲刺4
    alpha冲刺3
    设计模式——桥接模式
    Java基础——关键字
  • 原文地址:https://www.cnblogs.com/childhooding/p/4461510.html
Copyright © 2020-2023  润新知