詳解Android 教你打造高效的圖片加載框架
1、概述
優(yōu)秀的圖片加載框架不要太多,什么UIL , Volley ,Picasso,Imageloader等等。但是作為一名合格的程序猿,必須懂其中的實(shí)現(xiàn)原理,于是乎,今天我就帶大家一起來(lái)設(shè)計(jì)一個(gè)加載網(wǎng)絡(luò)、本地的圖片框架。有人可能會(huì)說(shuō),自己寫(xiě)會(huì)不會(huì)很渣,運(yùn)行效率,內(nèi)存溢出神馬的。放心,我們拿demo說(shuō)話,拼得就是速度,奏事這么任性。
關(guān)于加載本地圖片,當(dāng)然了,我手機(jī)圖片比較少,7000來(lái)張:
1、首先肯定不能內(nèi)存溢出,但是現(xiàn)在像素那么高,怎么才能保證呢?我相信利用LruCache統(tǒng)一管理你的圖片是個(gè)不二的選擇,所有的圖片從LruCache里面取,保證所有的圖片的內(nèi)存不會(huì)超過(guò)預(yù)設(shè)的空間。
2、加載速度要?jiǎng)倓偟?,我一用力,滑?dòng)到3000張的位置,你要是還在從第一張給我加載,你以為我打dota呢。所以我們需要引入加載策略,我們不能FIFO,我們選擇LIFO,當(dāng)前呈現(xiàn)給用戶的,最新加載;當(dāng)前未呈現(xiàn)的,選擇加載。
3、使用方便。一般圖片都會(huì)使用GridView作為控件,在getView里面進(jìn)行圖片加載,當(dāng)然了為了不錯(cuò)亂,可能還需要用戶去自己setTag,自己寫(xiě)回調(diào)設(shè)置圖片。當(dāng)然了,我們不需要這么麻煩,一句話IoadImage(imageview,path)即可,剩下的請(qǐng)交給我們的圖片加載框架處理。
做到以上幾點(diǎn),關(guān)于本地的圖片加載應(yīng)該就木有什么問(wèn)題了。
關(guān)于加載網(wǎng)絡(luò)圖片,其實(shí)原理差不多,就多了個(gè)是否啟用硬盤(pán)緩存的選項(xiàng),如果啟用了,加載時(shí),先從內(nèi)存中查找,然后從硬盤(pán)上找,最后去網(wǎng)絡(luò)下載。下載完成后,別忘了寫(xiě)入硬盤(pán),加入內(nèi)存緩存。如果沒(méi)有啟用,那么就直接從網(wǎng)絡(luò)壓縮獲取,加入內(nèi)存即可。
2、效果圖
終于扯完了,接下來(lái),簡(jiǎn)單看個(gè)效果圖,關(guān)于加載本地圖片的效果圖:可以從Android 超高仿微信圖片選擇器 圖片該這么加載這篇博客中下載Demo運(yùn)行。
下面演示一個(gè)網(wǎng)絡(luò)加載圖片的例子:
80多張從網(wǎng)絡(luò)加載的圖片,可以看到我直接拖到最后,基本是呈現(xiàn)在用戶眼前的最先加載,要是從第一張到80多,估計(jì)也是醉了。
此外:圖片來(lái)自老郭的博客,感謝?。?!ps:如果你覺(jué)得圖片不勁爆,Day Day Up找老郭去。
3、完全解析
1、關(guān)于圖片的壓縮
不管是從網(wǎng)絡(luò)還是本地的圖片,加載都需要進(jìn)行壓縮,然后顯示:
用戶要你壓縮顯示,會(huì)給我們什么?一個(gè)imageview,一個(gè)path,我們的職責(zé)就是壓縮完成后顯示上去。
1、本地圖片的壓縮
a、獲得imageview想要顯示的大小
想要壓縮,我們第一步應(yīng)該是獲得imageview想要顯示的大小,沒(méi)大小肯定沒(méi)辦法壓縮?
那么如何獲得imageview想要顯示的大小呢?
/** * 根據(jù)ImageView獲適當(dāng)?shù)膲嚎s的寬和高 * * @param imageView * @return */ public static ImageSize getImageViewSize(ImageView imageView) { ImageSize imageSize = new ImageSize(); DisplayMetrics displayMetrics = imageView.getContext().getResources() .getDisplayMetrics(); LayoutParams lp = imageView.getLayoutParams(); int width = imageView.getWidth();// 獲取imageview的實(shí)際寬度 if (width <= 0) { width = lp.width;// 獲取imageview在layout中聲明的寬度 } if (width <= 0) { // width = imageView.getMaxWidth();// 檢查最大值 width = getImageViewFieldValue(imageView, "mMaxWidth"); } if (width <= 0) { width = displayMetrics.widthPixels; } int height = imageView.getHeight();// 獲取imageview的實(shí)際高度 if (height <= 0) { height = lp.height;// 獲取imageview在layout中聲明的寬度 } if (height <= 0) { height = getImageViewFieldValue(imageView, "mMaxHeight");// 檢查最大值 } if (height <= 0) { height = displayMetrics.heightPixels; } imageSize.width = width; imageSize.height = height; return imageSize; } public static class ImageSize { int width; int height; }
可以看到,我們拿到imageview以后:
首先企圖通過(guò)getWidth獲取顯示的寬;有些時(shí)候,這個(gè)getWidth返回的是0;
那么我們?cè)偃タ纯此袥](méi)有在布局文件中書(shū)寫(xiě)寬;
如果布局文件中也沒(méi)有精確值,那么我們?cè)偃タ纯此袥](méi)有設(shè)置最大值;
如果最大值也沒(méi)設(shè)置,那么我們只有拿出我們的終極方案,使用我們的屏幕寬度;
總之,不能讓它任性,我們一定要拿到一個(gè)合適的顯示值。
可以看到這里或者最大寬度,我們用的反射,而不是getMaxWidth();維薩呢,因?yàn)間etMaxWidth竟然要API 16,我也是醉了;為了兼容性,我們采用反射的方案。反射的代碼就不貼了。
b、設(shè)置合適的inSampleSize
我們獲得想要顯示的大小,為了什么,還不是為了和圖片的真正的寬高做比較,拿到一個(gè)合適的inSampleSize,去對(duì)圖片進(jìn)行壓縮么。
那么首先應(yīng)該是拿到圖片的寬和高:
// 獲得圖片的寬和高,并不把圖片加載到內(nèi)存中 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options);
這三行就成功獲取圖片真正的寬和高了,存在我們的options里面;
然后我們就可以happy的去計(jì)算inSampleSize了:
/** * 根據(jù)需求的寬和高以及圖片實(shí)際的寬和高計(jì)算SampleSize * * @param options * @param width * @param height * @return */ public static int caculateInSampleSize(Options options, int reqWidth, int reqHeight) { int width = options.outWidth; int height = options.outHeight; int inSampleSize = 1; if (width > reqWidth || height > reqHeight) { int widthRadio = Math.round(width * 1.0f / reqWidth); int heightRadio = Math.round(height * 1.0f / reqHeight); inSampleSize = Math.max(widthRadio, heightRadio); } return inSampleSize; }
options里面存了實(shí)際的寬和高;reqWidth和reqHeight就是我們之前得到的想要顯示的大??;經(jīng)過(guò)比較,得到一個(gè)合適的inSampleSize;
有了inSampleSize:
options.inSampleSize = ImageSizeUtil.caculateInSampleSize(options, width, height); // 使用獲得到的InSampleSize再次解析圖片 options.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeFile(path, options); return bitmap;
經(jīng)過(guò)這幾行,就完成圖片的壓縮了。
上述是本地圖片的壓縮,那么如果是網(wǎng)絡(luò)圖片呢?
2、網(wǎng)絡(luò)圖片的壓縮
a、直接下載存到sd卡,然后采用本地的壓縮方案。這種方式當(dāng)前是在硬盤(pán)緩存開(kāi)啟的情況下,如果沒(méi)有開(kāi)啟呢?
b、使用BitmapFactory.decodeStream(is, null, opts);
/** * 根據(jù)url下載圖片在指定的文件 * * @param urlStr * @param file * @return */ public static Bitmap downloadImgByUrl(String urlStr, ImageView imageview) { FileOutputStream fos = null; InputStream is = null; try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); is = new BufferedInputStream(conn.getInputStream()); is.mark(is.available()); Options opts = new Options(); opts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts); //獲取imageview想要顯示的寬和高 ImageSize imageViewSize = ImageSizeUtil.getImageViewSize(imageview); opts.inSampleSize = ImageSizeUtil.caculateInSampleSize(opts, imageViewSize.width, imageViewSize.height); opts.inJustDecodeBounds = false; is.reset(); bitmap = BitmapFactory.decodeStream(is, null, opts); conn.disconnect(); return bitmap; } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } return null; }
基本和本地壓縮差不多,也是兩次取樣,當(dāng)然需要注意一點(diǎn),我們的is進(jìn)行了包裝,以便可以進(jìn)行reset();直接返回的is是不能使用兩次的。
到此,圖片壓縮說(shuō)完了。
2、圖片加載框架的架構(gòu)
我們的圖片壓縮加載完了,那么就應(yīng)該放入我們的LruCache,然后設(shè)置到我們的ImageView上。
好了,接下來(lái)我們來(lái)說(shuō)說(shuō)我們的這個(gè)框架的架構(gòu);
1、單例,包含一個(gè)LruCache用于管理我們的圖片;
2、任務(wù)隊(duì)列,我們每來(lái)一次加載圖片的請(qǐng)求,我們會(huì)封裝成Task存入我們的TaskQueue;
3、包含一個(gè)后臺(tái)線程,這個(gè)線程在第一次初始化實(shí)例的時(shí)候啟動(dòng),然后會(huì)一直在后臺(tái)運(yùn)行;任務(wù)呢?還記得我們有個(gè)任務(wù)隊(duì)列么,有隊(duì)列存任務(wù),得有人干活呀;所以,當(dāng)每來(lái)一次加載圖片請(qǐng)求的時(shí)候,我們同時(shí)發(fā)一個(gè)消息到后臺(tái)線程,后臺(tái)線程去使用線程池去TaskQueue去取一個(gè)任務(wù)執(zhí)行;
4、調(diào)度策略;3中說(shuō)了,后臺(tái)線程去TaskQueue去取一個(gè)任務(wù),這個(gè)任務(wù)不是隨便取的,有策略可以選擇,一個(gè)是FIFO,一個(gè)是LIFO,我傾向于后者。
好了,基本就這些結(jié)構(gòu),接下來(lái)看我們具體的實(shí)現(xiàn)。
3、具體的實(shí)現(xiàn)
1、構(gòu)造方法
public static ImageLoader getInstance(int threadCount, Type type) { if (mInstance == null) { synchronized (ImageLoader.class) { if (mInstance == null) { mInstance = new ImageLoader(threadCount, type); } } } return mInstance; }
這個(gè)就不用說(shuō)了,重點(diǎn)看我們的構(gòu)造方法
/** * 圖片加載類 * * @author zhy * */ public class ImageLoader { private static ImageLoader mInstance; /** * 圖片緩存的核心對(duì)象 */ private LruCache<String, Bitmap> mLruCache; /** * 線程池 */ private ExecutorService mThreadPool; private static final int DEAFULT_THREAD_COUNT = 1; /** * 隊(duì)列的調(diào)度方式 */ private Type mType = Type.LIFO; /** * 任務(wù)隊(duì)列 */ private LinkedList<Runnable> mTaskQueue; /** * 后臺(tái)輪詢線程 */ private Thread mPoolThread; private Handler mPoolThreadHandler; /** * UI線程中的Handler */ private Handler mUIHandler; private Semaphore mSemaphorePoolThreadHandler = new Semaphore(0); private Semaphore mSemaphoreThreadPool; private boolean isDiskCacheEnable = true; private static final String TAG = "ImageLoader"; public enum Type { FIFO, LIFO; } private ImageLoader(int threadCount, Type type) { init(threadCount, type); } /** * 初始化 * * @param threadCount * @param type */ private void init(int threadCount, Type type) { initBackThread(); // 獲取我們應(yīng)用的最大可用內(nèi)存 int maxMemory = (int) Runtime.getRuntime().maxMemory(); int cacheMemory = maxMemory / 8; mLruCache = new LruCache<String, Bitmap>(cacheMemory) { @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight(); } }; // 創(chuàng)建線程池 mThreadPool = Executors.newFixedThreadPool(threadCount); mTaskQueue = new LinkedList<Runnable>(); mType = type; mSemaphoreThreadPool = new Semaphore(threadCount); } /** * 初始化后臺(tái)輪詢線程 */ private void initBackThread() { // 后臺(tái)輪詢線程 mPoolThread = new Thread() { @Override public void run() { Looper.prepare(); mPoolThreadHandler = new Handler() { @Override public void handleMessage(Message msg) { // 線程池去取出一個(gè)任務(wù)進(jìn)行執(zhí)行 mThreadPool.execute(getTask()); try { mSemaphoreThreadPool.acquire(); } catch (InterruptedException e) { } } }; // 釋放一個(gè)信號(hào)量 mSemaphorePoolThreadHandler.release(); Looper.loop(); }; }; mPoolThread.start(); }
在貼構(gòu)造的時(shí)候,順便貼出所有的成員變量;
在構(gòu)造中我們調(diào)用init,init中可以設(shè)置后臺(tái)加載圖片線程數(shù)量和加載策略;init中首先初始化后臺(tái)線程initBackThread(),可以看到這個(gè)后臺(tái)線程,實(shí)際上是個(gè)Looper最終在那不斷的loop,我們還初始化了一個(gè)mPoolThreadHandler用于發(fā)送消息到此線程;
接下來(lái)就是初始化mLruCache , mThreadPool ,mTaskQueue 等;
2、loadImage
構(gòu)造完成以后,當(dāng)然是使用了,用戶調(diào)用loadImage傳入(final String path, final ImageView imageView,final boolean isFromNet)就可以完成本地或者網(wǎng)絡(luò)圖片的加載。
/** * 根據(jù)path為imageview設(shè)置圖片 * * @param path * @param imageView */ public void loadImage(final String path, final ImageView imageView, final boolean isFromNet) { imageView.setTag(path); if (mUIHandler == null) { mUIHandler = new Handler() { public void handleMessage(Message msg) { // 獲取得到圖片,為imageview回調(diào)設(shè)置圖片 ImgBeanHolder holder = (ImgBeanHolder) msg.obj; Bitmap bm = holder.bitmap; ImageView imageview = holder.imageView; String path = holder.path; // 將path與getTag存儲(chǔ)路徑進(jìn)行比較 if (imageview.getTag().toString().equals(path)) { imageview.setImageBitmap(bm); } }; }; } // 根據(jù)path在緩存中獲取bitmap Bitmap bm = getBitmapFromLruCache(path); if (bm != null) { refreashBitmap(path, imageView, bm); } else { addTask(buildTask(path, imageView, isFromNet)); } }
首先我們?yōu)閕mageview.setTag;然后初始化一個(gè)mUIHandler,不用猜,這個(gè)mUIHandler用戶更新我們的imageview,因?yàn)檫@個(gè)方法肯定是主線程調(diào)用的。
然后調(diào)用:getBitmapFromLruCache(path);根據(jù)path在緩存中獲取bitmap;如果找到那么直接去設(shè)置我們的圖片;
private void refreashBitmap(final String path, final ImageView imageView, Bitmap bm) { Message message = Message.obtain(); ImgBeanHolder holder = new ImgBeanHolder(); holder.bitmap = bm; holder.path = path; holder.imageView = imageView; message.obj = holder; mUIHandler.sendMessage(message); }
可以看到,如果找到圖片,則直接使用UIHandler去發(fā)送一個(gè)消息,當(dāng)然了攜帶了一些必要的參數(shù),然后UIHandler的handleMessage中完成圖片的設(shè)置;
handleMessage中拿到path,bitmap,imageview;記得必須要:
// 將path與getTag存儲(chǔ)路徑進(jìn)行比較 if (imageview.getTag().toString().equals(path)) { imageview.setImageBitmap(bm); }
否則會(huì)造成圖片混亂。
如果沒(méi)找到,則通過(guò)buildTask去新建一個(gè)任務(wù),在addTask到任務(wù)隊(duì)列。
buildTask就比較復(fù)雜了,因?yàn)檫€涉及到本地和網(wǎng)絡(luò),所以我們先看addTask代碼:
private synchronized void addTask(Runnable runnable) { mTaskQueue.add(runnable); // if(mPoolThreadHandler==null)wait(); try { if (mPoolThreadHandler == null) mSemaphorePoolThreadHandler.acquire(); } catch (InterruptedException e) { } mPoolThreadHandler.sendEmptyMessage(0x110); }
很簡(jiǎn)單,就是runnable加入TaskQueue,與此同時(shí)使用mPoolThreadHandler(這個(gè)handler還記得么,用于和我們后臺(tái)線程交互。)去發(fā)送一個(gè)消息給后臺(tái)線程,叫它去取出一個(gè)任務(wù)執(zhí)行;具體代碼:
mPoolThreadHandler = new Handler() { @Override public void handleMessage(Message msg) { // 線程池去取出一個(gè)任務(wù)進(jìn)行執(zhí)行 mThreadPool.execute(getTask());
直接使用mThreadPool線程池,然后使用getTask去取一個(gè)任務(wù)。
/** * 從任務(wù)隊(duì)列取出一個(gè)方法 * * @return */ private Runnable getTask() { if (mType == Type.FIFO) { return mTaskQueue.removeFirst(); } else if (mType == Type.LIFO) { return mTaskQueue.removeLast(); } return null; }
getTask代碼也比較簡(jiǎn)單,就是根據(jù)Type從任務(wù)隊(duì)列頭或者尾進(jìn)行取任務(wù)。
現(xiàn)在你會(huì)不會(huì)好奇,任務(wù)里面到底什么代碼?其實(shí)我們也就剩最后一段代碼了buildTask
/** * 根據(jù)傳入的參數(shù),新建一個(gè)任務(wù) * * @param path * @param imageView * @param isFromNet * @return */ private Runnable buildTask(final String path, final ImageView imageView, final boolean isFromNet) { return new Runnable() { @Override public void run() { Bitmap bm = null; if (isFromNet) { File file = getDiskCacheDir(imageView.getContext(), md5(path)); if (file.exists())// 如果在緩存文件中發(fā)現(xiàn) { Log.e(TAG, "find image :" + path + " in disk cache ."); bm = loadImageFromLocal(file.getAbsolutePath(), imageView); } else { if (isDiskCacheEnable)// 檢測(cè)是否開(kāi)啟硬盤(pán)緩存 { boolean downloadState = DownloadImgUtils .downloadImgByUrl(path, file); if (downloadState)// 如果下載成功 { Log.e(TAG, "download image :" + path + " to disk cache . path is " + file.getAbsolutePath()); bm = loadImageFromLocal(file.getAbsolutePath(), imageView); } } else // 直接從網(wǎng)絡(luò)加載 { Log.e(TAG, "load image :" + path + " to memory."); bm = DownloadImgUtils.downloadImgByUrl(path, imageView); } } } else { bm = loadImageFromLocal(path, imageView); } // 3、把圖片加入到緩存 addBitmapToLruCache(path, bm); refreashBitmap(path, imageView, bm); mSemaphoreThreadPool.release(); } }; } private Bitmap loadImageFromLocal(final String path, final ImageView imageView) { Bitmap bm; // 加載圖片 // 圖片的壓縮 // 1、獲得圖片需要顯示的大小 ImageSize imageSize = ImageSizeUtil.getImageViewSize(imageView); // 2、壓縮圖片 bm = decodeSampledBitmapFromPath(path, imageSize.width, imageSize.height); return bm; }
我們新建任務(wù),說(shuō)明在內(nèi)存中沒(méi)有找到緩存的bitmap;我們的任務(wù)就是去根據(jù)path加載壓縮后的bitmap返回即可,然后加入LruCache,設(shè)置回調(diào)顯示。
首先我們判斷是否是網(wǎng)絡(luò)任務(wù)?
如果是,首先去硬盤(pán)緩存中找一下,(硬盤(pán)中文件名為:根據(jù)path生成的md5為名稱)。
如果硬盤(pán)緩存中沒(méi)有,那么去判斷是否開(kāi)啟了硬盤(pán)緩存:
開(kāi)啟了的話:下載圖片,使用loadImageFromLocal本地加載圖片的方式進(jìn)行加載(壓縮的代碼前面已經(jīng)詳細(xì)說(shuō)過(guò));
如果沒(méi)有開(kāi)啟:則直接從網(wǎng)絡(luò)獲?。▔嚎s獲取的代碼,前面詳細(xì)說(shuō)過(guò));
如果不是網(wǎng)絡(luò)圖片:直接loadImageFromLocal本地加載圖片的方式進(jìn)行加載
經(jīng)過(guò)上面,就獲得了bitmap;然后加入addBitmapToLruCache,refreashBitmap回調(diào)顯示圖片。
/** * 將圖片加入LruCache * * @param path * @param bm */ protected void addBitmapToLruCache(String path, Bitmap bm) { if (getBitmapFromLruCache(path) == null) { if (bm != null) mLruCache.put(path, bm); } }
到此,我們所有的代碼就分析完成了;
緩存的圖片位置:在SD卡的Android/data/項(xiàng)目packageName/cache中:
不過(guò)有些地方需要注意:就是在代碼中,你會(huì)看到一些信號(hào)量的身影:
第一個(gè):mSemaphorePoolThreadHandler = new Semaphore(0); 用于控制我們的mPoolThreadHandler的初始化完成,我們?cè)谑褂胢PoolThreadHandler會(huì)進(jìn)行判空,如果為null,會(huì)通過(guò)mSemaphorePoolThreadHandler.acquire()進(jìn)行阻塞;當(dāng)mPoolThreadHandler初始化結(jié)束,我們會(huì)調(diào)用.release();解除阻塞。
第二個(gè):mSemaphoreThreadPool = new Semaphore(threadCount);這個(gè)信號(hào)量的數(shù)量和我們加載圖片的線程個(gè)數(shù)一致;每取一個(gè)任務(wù)去執(zhí)行,我們會(huì)讓信號(hào)量減一;每完成一個(gè)任務(wù),會(huì)讓信號(hào)量+1,再去取任務(wù);目的是什么呢?為什么當(dāng)我們的任務(wù)到來(lái)時(shí),如果此時(shí)在沒(méi)有空閑線程,任務(wù)則一直添加到TaskQueue中,當(dāng)線程完成任務(wù),可以根據(jù)策略去TaskQueue中去取任務(wù),只有這樣,我們的LIFO才有意義。
到此,我們的圖片加載框架就結(jié)束了,你可以嘗試下加載本地,或者去加載網(wǎng)絡(luò)大量的圖片,拼一拼加載速度~~~
4、MainActivity
現(xiàn)在是使用的時(shí)刻~~
我在MainActivity中,我使用了Fragment,下面我貼下Fragment和布局文件的代碼,具體的,大家自己看代碼:
package com.example.demo_zhy_18_networkimageloader; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; import com.zhy.utils.ImageLoader; import com.zhy.utils.ImageLoader.Type; import com.zhy.utils.Images; public class ListImgsFragment extends Fragment { private GridView mGridView; private String[] mUrlStrs = Images.imageThumbUrls; private ImageLoader mImageLoader; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mImageLoader = ImageLoader.getInstance(3, Type.LIFO); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_list_imgs, container, false); mGridView = (GridView) view.findViewById(R.id.id_gridview); setUpAdapter(); return view; } private void setUpAdapter() { if (getActivity() == null || mGridView == null) return; if (mUrlStrs != null) { mGridView.setAdapter(new ListImgItemAdaper(getActivity(), 0, mUrlStrs)); } else { mGridView.setAdapter(null); } } private class ListImgItemAdaper extends ArrayAdapter<String> { public ListImgItemAdaper(Context context, int resource, String[] datas) { super(getActivity(), 0, datas); Log.e("TAG", "ListImgItemAdaper"); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate( R.layout.item_fragment_list_imgs, parent, false); } ImageView imageview = (ImageView) convertView .findViewById(R.id.id_img); imageview.setImageResource(R.drawable.pictures_no); mImageLoader.loadImage(getItem(position), imageview, true); return convertView; } } }
可以看到我們?cè)趃etView中,使用mImageLoader.loadImage一行即完成了圖片的加載。
fragment_list_imgs.xml
<GridView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/id_gridview" android:layout_width="match_parent" android:layout_height="match_parent" android:horizontalSpacing="3dp" android:verticalSpacing="3dp" android:numColumns="3" > </GridView> item_fragment_list_imgs.xml <ImageView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/id_img" android:layout_width="match_parent" android:layout_height="120dp" android:scaleType="centerCrop" > </ImageView>
好了,到此結(jié)束~~~有任何bug或者意見(jiàn)歡迎留言~
demo下載:demo
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android Handler之消息循環(huán)的深入解析
本篇文章是對(duì)Handler消息循環(huán)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05Android編程實(shí)現(xiàn)二維碼的生成與解析
這篇文章主要介紹了Android編程實(shí)現(xiàn)二維碼的生成與解析方法,結(jié)合實(shí)例分析了Android二維碼的生成與讀取二維碼的相關(guān)技巧,并提供了二維碼jar包供讀者下載,需要的朋友可以參考下2015-11-11Android APT 實(shí)現(xiàn)控件注入框架SqInject的示例
這篇文章主要介紹了Android APT 實(shí)現(xiàn)控件注入框架SqInject的示例,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-03-03Android 中Fragment與Activity通訊的詳解
這篇文章主要介紹了Android 中Fragment與Activity通訊的詳解的相關(guān)資料,希望通過(guò)本文能幫助到大家,讓大家理解掌握如何通信的,需要的朋友可以參考下2017-10-10Handler消息傳遞機(jī)制類引入及執(zhí)行流程詳解
這篇文章主要為大家介紹了Handler消息傳遞機(jī)制類引入及執(zhí)行流程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04Android開(kāi)發(fā)工程中集成mob短信驗(yàn)證碼功能的方法
這篇文章主要介紹了Android開(kāi)發(fā)工程中集成mob短信驗(yàn)證碼功能的方法,感興趣的小伙伴們可以參考一下2016-05-05Android實(shí)現(xiàn)Activity界面切換添加動(dòng)畫(huà)特效的方法
這篇文章主要介紹了Android實(shí)現(xiàn)Activity界面切換添加動(dòng)畫(huà)特效的方法,非常實(shí)用的技巧,需要的朋友可以參考下2014-08-08Android超詳細(xì)講解彈出多選框的實(shí)現(xiàn)
這篇文章主要介紹了在Android開(kāi)發(fā)中如何實(shí)現(xiàn)彈出多選框的功能,多選框是很常見(jiàn)的操作控件,感興趣的朋友都來(lái)一起看看吧2022-03-03