溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

android 安卓異步加載網(wǎng)絡(luò)圖片,與viewpager結(jié)合使用示例

發(fā)布時(shí)間:2020-07-01 03:54:59 來(lái)源:網(wǎng)絡(luò) 閱讀:1289 作者:careylwq 欄目:移動(dòng)開發(fā)
【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 {

	// 軟引用,使用內(nèi)存做臨時(shí)緩存 (程序退出,或內(nèi)存不夠則清除軟引用)
	private HashMap<String, SoftReference<Drawable>> p_w_picpathCache;

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

	/**
	 * 定義回調(diào)接口
	 */
	public interface ImageCallback {
		public void p_w_picpathLoaded(Drawable p_w_picpathDrawable, String p_w_picpathUrl);
	}

	/**
	 * 創(chuàng)建子線程加載圖片
	 * 子線程加載完圖片交給handler處理(子線程不能更新ui,而handler處在主線程,可以更新ui)
	 * handler又交給p_w_picpathCallback,p_w_picpathCallback須要自己來(lái)實(shí)現(xiàn),在這里可以對(duì)回調(diào)參數(shù)進(jìn)行處理
	 * @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);//執(zhí)行回調(diào)
				return drawable;
			}
		}

		/**
		 * 在主線程里執(zhí)行回調(diào),更新視圖
		 */
		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);
			}
		};

		
		/**
		 * 創(chuàng)建子線程訪問(wèn)網(wǎng)絡(luò)并加載圖片 ,把結(jié)果交給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的區(qū)別)
	 */
	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問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI