温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

android 安卓异步加载网络图片,与viewpager结合使用示例

发布时间:2020-07-01 03:54:59 来源:网络 阅读:1281 作者:careylwq 栏目:移动开发
【1】异步加载图片类AsyncImageLoader
package com.example.testdddleapk.cus;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

/**
 * 异步加载图片
 */
public class AsyncImageLoader {

	// 软引用,使用内存做临时缓存 (程序退出,或内存不够则清除软引用)
	private HashMap<String, SoftReference<Drawable>> p_w_picpathCache;

	public AsyncImageLoader() {
		p_w_picpathCache = new HashMap<String, SoftReference<Drawable>>();
	}

	/**
	 * 定义回调接口
	 */
	public interface ImageCallback {
		public void p_w_picpathLoaded(Drawable p_w_picpathDrawable, String p_w_picpathUrl);
	}

	/**
	 * 创建子线程加载图片
	 * 子线程加载完图片交给handler处理(子线程不能更新ui,而handler处在主线程,可以更新ui)
	 * handler又交给p_w_picpathCallback,p_w_picpathCallback须要自己来实现,在这里可以对回调参数进行处理
	 * @param p_w_picpathUrl :须要加载的图片url
	 * @param p_w_picpathCallback:
	 * @return
	 */
	public Drawable loadDrawable(final String p_w_picpathUrl,final ImageCallback p_w_picpathCallback) {
		//如果缓存中存在图片  ,则首先使用缓存
		if (p_w_picpathCache.containsKey(p_w_picpathUrl)) {
			SoftReference<Drawable> softReference = p_w_picpathCache.get(p_w_picpathUrl);
			Drawable drawable = softReference.get();
			if (drawable != null) {
				System.out.println("loadDrawable");
				p_w_picpathCallback.p_w_picpathLoaded(drawable, p_w_picpathUrl);//执行回调
				return drawable;
			}
		}

		/**
		 * 在主线程里执行回调,更新视图
		 */
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				System.out.println("handleMessage");
				p_w_picpathCallback.p_w_picpathLoaded((Drawable) message.obj, p_w_picpathUrl);
			}
		};

		
		/**
		 * 创建子线程访问网络并加载图片 ,把结果交给handler处理
		 */
		new Thread() {
			@Override
			public void run() {
				Drawable drawable = loadImageFromUrl(p_w_picpathUrl);
				// 下载完的图片放到缓存里
				p_w_picpathCache.put(p_w_picpathUrl, new SoftReference<Drawable>(drawable));
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		}.start();
		return null;
	}
	
	/**
	 * 下载图片  (注意HttpClient 和httpUrlConnection的区别)
	 */
	public Drawable loadImageFromUrl(String url) {

		try {
			HttpClient client = new DefaultHttpClient();
			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000*15);
			HttpGet get = new HttpGet(url);
			HttpResponse response;
			response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				Drawable d = Drawable.createFromStream(entity.getContent(),"src");
				return d;
			} else {
				return null;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	//清除缓存
	public void clearCache() {
		if (this.p_w_picpathCache.size() > 0) {
			this.p_w_picpathCache.clear();
		}
	}

}

【2】 pagerAdapter的instantiateItem方法

@SuppressLint("NewApi") @Override
public Object instantiateItem(final ViewGroup container, final int position) {
        String url=imgsUrls[position];
	Drawable cachedImage = asyncImageLoader.loadDrawable(url, new ImageCallback() {
	    @SuppressLint("NewApi") public void p_w_picpathLoaded(Drawable p_w_picpathDrawable,String p_w_picpathUrl) {
		ImageView img=(ImageView) viewList.get(position).findViewById(R.id.img);
		img.setBackground(p_w_picpathDrawable);
		container.addView(view);
	    }
	});
	return viewList.get(position);
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI