Android 框架練成 教你打造高效的圖片載入框架

發表於2015-05-25

1、概述

優秀的圖片載入框架不要太多,什麼UIL , Volley ,Picasso,Imageloader等等。但是作為一名合格的程式猿,必須懂其中的實現原理,於是乎,今天我就帶大家一起來設計一個載入網路、本地的圖片框架。有人可能會說,自己寫會不會很渣,執行效率,記憶體溢位神馬的。放心,我們拿demo說話,拼得就是速度,奏事這麼任性。

好了,如果你看過之前的博文,類似Android Handler 非同步訊息處理機制的妙用 建立強大的圖片載入類,可能會對接下來文章理解會有很大的幫助。沒有的話,就跟我往下繼續走吧,也不要去看了。

關於載入本地圖片,當然了,我手機圖片比較少,7000來張:

1、首先肯定不能記憶體溢位,但是尼瑪現在畫素那麼高,怎麼才能保證呢?我相信利用LruCache統一管理你的圖片是個不二的選擇,所有的圖片從LruCache裡面取,保證所有的圖片的記憶體不會超過預設的空間。

2、載入速度要剛剛的,我一用力,滑動到3000張的位置,你要是還在從第一張給我載入,尼瑪,你以為我打dota呢。所以我們需要引入載入策略,我們不能FIFO,我們選擇LIFO,當前呈現給使用者的,最新載入;當前未呈現的,選擇載入。

3、使用方便。一般圖片都會使用GridView作為控制元件,在getView裡面進行圖片載入,當然了為了不錯亂,可能還需要使用者去自己setTag,自己寫回撥設定圖片。當然了,我們不需要這麼麻煩,一句話IoadImage(imageview,path)即可,剩下的請交給我們的圖片載入框架處理。

做到以上幾點,關於本地的圖片載入應該就木有什麼問題了。

關於載入網路圖片,其實原理差不多,就多了個是否啟用硬碟快取的選項,如果啟用了,載入時,先從記憶體中查詢,然後從硬碟上找,最後去網路下載。下載完成後,別忘了寫入硬碟,加入記憶體快取。如果沒有啟用,那麼就直接從網路壓縮獲取,加入記憶體即可。

2、效果圖

終於扯完了,接下來,簡單看個效果圖,關於載入本地圖片的效果圖:可以從Android 超高仿微信圖片選擇器 圖片該這麼載入這篇部落格中下載Demo執行。

下面演示一個網路載入圖片的例子:

載入中...

80多張從網路載入的圖片,可以看到我直接拖到最後,基本是呈現在使用者眼前的最先載入,要是從第一張到80多,估計也是醉了。

此外:圖片來自老郭的部落格,感謝!!!ps:如果你覺得圖片不勁爆,Day Day Up找老郭去。

3、完全解析

1、關於圖片的壓縮

不管是從網路還是本地的圖片,載入都需要進行壓縮,然後顯示:

使用者要你壓縮顯示,會給我們什麼?一個imageview,一個path,我們的職責就是壓縮完成後顯示上去。

1、本地圖片的壓縮


a、獲得imageview想要顯示的大小

想要壓縮,我們第一步應該是獲得imageview想要顯示的大小,沒大小肯定沒辦法壓縮?

那麼如何獲得imageview想要顯示的大小呢?

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
     * 根據ImageView獲適當的壓縮的寬和高
     *
     * @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的實際寬度
        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的實際高度
        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以後:

 

首先企圖通過getWidth獲取顯示的寬;有些時候,這個getWidth返回的是0;

那麼我們再去看看它有沒有在佈局檔案中書寫寬;

如果佈局檔案中也沒有精確值,那麼我們再去看看它有沒有設定最大值;

如果最大值也沒設定,那麼我們只有拿出我們的終極方案,使用我們的螢幕寬度;

總之,不能讓它任性,我們一定要拿到一個合適的顯示值。

可以看到這裡或者最大寬度,我們用的反射,而不是getMaxWidth();維薩呢,因為getMaxWidth竟然要API 16,我也是醉了;為了相容性,我們採用反射的方案。反射的程式碼就不貼了。

b、設定合適的inSampleSize

我們獲得想要顯示的大小,為了什麼,還不是為了和圖片的真正的寬高做比較,拿到一個合適的inSampleSize,去對圖片進行壓縮麼。

那麼首先應該是拿到圖片的寬和高:

 

?
1
2
3
4
// 獲得圖片的寬和高,並不把圖片載入到記憶體中
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

這三行就成功獲取圖片真正的寬和高了,存在我們的options裡面;

 

然後我們就可以happy的去計算inSampleSize了:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
     * 根據需求的寬和高以及圖片實際的寬和高計算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裡面存了實際的寬和高;reqWidth和reqHeight就是我們之前得到的想要顯示的大小;經過比較,得到一個合適的inSampleSize;

 

有了inSampleSize:

 

?
1
2
3
4
5
6
7
options.inSampleSize = ImageSizeUtil.caculateInSampleSize(options,
                width, height);
 
        // 使用獲得到的InSampleSize再次解析圖片
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        return bitmap;

經過這幾行,就完成圖片的壓縮了。

 

上述是本地圖片的壓縮,那麼如果是網路圖片呢?

2、網路圖片的壓縮


a、直接下載存到sd卡,然後採用本地的壓縮方案。這種方式當前是在硬碟快取開啟的情況下,如果沒有開啟呢?

b、使用BitmapFactory.decodeStream(is, null, opts);

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
     * 根據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;
 
    }
基本和本地壓縮差不多,也是兩次取樣,當然需要注意一點,我們的is進行了包裝,以便可以進行reset();直接返回的is是不能使用兩次的。

 

到此,圖片壓縮說完了。

2、圖片載入框架的架構

我們的圖片壓縮載入完了,那麼就應該放入我們的LruCache,然後設定到我們的ImageView上。

好了,接下來我們來說說我們的這個框架的架構;

1、單例,包含一個LruCache用於管理我們的圖片;

2、任務佇列,我們每來一次載入圖片的請求,我們會封裝成Task存入我們的TaskQueue;

3、包含一個後臺執行緒,這個執行緒在第一次初始化例項的時候啟動,然後會一直在後臺執行;任務呢?還記得我們有個任務佇列麼,有佇列存任務,得有人幹活呀;所以,當每來一次載入圖片請求的時候,我們同時發一個訊息到後臺執行緒,後臺執行緒去使用執行緒池去TaskQueue去取一個任務執行;

4、排程策略;3中說了,後臺執行緒去TaskQueue去取一個任務,這個任務不是隨便取的,有策略可以選擇,一個是FIFO,一個是LIFO,我傾向於後者。

好了,基本就這些結構,接下來看我們具體的實現。

3、具體的實現

1、構造方法

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static ImageLoader getInstance(int threadCount, Type type)
    {
        if (mInstance == null)
        {
            synchronized (ImageLoader.class)
            {
                if (mInstance == null)
                {
                    mInstance = new ImageLoader(threadCount, type);
                }
            }
        }
        return mInstance;
    }

這個就不用說了,重點看我們的構造方法

 

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
 * 圖片載入類
 *
 * @author zhy
 *
 */
public class ImageLoader
{
    private static ImageLoader mInstance;
 
    /**
     * 圖片快取的核心物件
     */
    private LruCache<string, bitmap=""> mLruCache;
    /**
     * 執行緒池
     */
    private ExecutorService mThreadPool;
    private static final int DEAFULT_THREAD_COUNT = 1;
    /**
     * 佇列的排程方式
     */
    private Type mType = Type.LIFO;
    /**
     * 任務佇列
     */
    private LinkedList<runnable> mTaskQueue;
    /**
     * 後臺輪詢執行緒
     */
    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();
 
        // 獲取我們應用的最大可用記憶體
        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();
            }
 
        };
 
        // 建立執行緒池
        mThreadPool = Executors.newFixedThreadPool(threadCount);
        mTaskQueue = new LinkedList<runnable>();
        mType = type;
        mSemaphoreThreadPool = new Semaphore(threadCount);
    }
 
    /**
     * 初始化後臺輪詢執行緒
     */
    private void initBackThread()
    {
        // 後臺輪詢執行緒
        mPoolThread = new Thread()
        {
            @Override
            public void run()
            {
                Looper.prepare();
                mPoolThreadHandler = new Handler()
                {
                    @Override
                    public void handleMessage(Message msg)
                    {
                        // 執行緒池去取出一個任務進行執行
                        mThreadPool.execute(getTask());
                        try
                        {
                            mSemaphoreThreadPool.acquire();
                        } catch (InterruptedException e)
                        {
                        }
                    }
                };
                // 釋放一個訊號量
                mSemaphorePoolThreadHandler.release();
                Looper.loop();
            };
        };
 
        mPoolThread.start();
    }</runnable></string,></runnable></string,>

在貼構造的時候,順便貼出所有的成員變數;

 

在構造中我們呼叫init,init中可以設定後臺載入圖片執行緒數量和載入策略;init中首先初始化後臺執行緒initBackThread(),可以看到這個後臺執行緒,實際上是個Looper最終在那不斷的loop,我們還初始化了一個mPoolThreadHandler用於傳送訊息到此執行緒;

接下來就是初始化mLruCache , mThreadPool ,mTaskQueue 等;

2、loadImage

構造完成以後,當然是使用了,使用者呼叫loadImage傳入(final String path, final ImageView imageView,final boolean isFromNet)就可以完成本地或者網路圖片的載入。

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
     * 根據path為imageview設定圖片
     *
     * @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回撥設定圖片
                    ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
                    Bitmap bm = holder.bitmap;
                    ImageView imageview = holder.imageView;
                    String path = holder.path;
                    // 將path與getTag儲存路徑進行比較
                    if (imageview.getTag().toString().equals(path))
                    {
                        imageview.setImageBitmap(bm);
                    }
                };
            };
        }
 
        // 根據path在快取中獲取bitmap
        Bitmap bm = getBitmapFromLruCache(path);
 
        if (bm != null)
        {
            refreashBitmap(path, imageView, bm);
        } else
        {
            addTask(buildTask(path, imageView, isFromNet));
        }
 
    }

首先我們為imageview.setTag;然後初始化一個mUIHandler,不用猜,這個mUIHandler使用者更新我們的imageview,因為這個方法肯定是主執行緒呼叫的。 

然後呼叫:getBitmapFromLruCache(path);根據path在快取中獲取bitmap;如果找到那麼直接去設定我們的圖片;

 

?
1
2
3
4
5
6
7
8
9
10
11
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去傳送一個訊息,當然了攜帶了一些必要的引數,然後UIHandler的handleMessage中完成圖片的設定; 

handleMessage中拿到path,bitmap,imageview;記得必須要:

// 將path與getTag儲存路徑進行比較
if (imageview.getTag().toString().equals(path))
{
imageview.setImageBitmap(bm);
}

否則會造成圖片混亂。

如果沒找到,則通過buildTask去新建一個任務,在addTask到任務佇列。

buildTask就比較複雜了,因為還涉及到本地和網路,所以我們先看addTask程式碼: 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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);
    }

很簡單,就是runnable加入TaskQueue,與此同時使用mPoolThreadHandler(這個handler還記得麼,用於和我們後臺執行緒互動。)去傳送一個訊息給後臺執行緒,叫它去取出一個任務執行;具體程式碼: 
?
1
2
3
4
5
6
7
mPoolThreadHandler = new Handler()
                {
                    @Override
                    public void handleMessage(Message msg)
                    {
                        // 執行緒池去取出一個任務進行執行
                        mThreadPool.execute(getTask());

直接使用mThreadPool執行緒池,然後使用getTask去取一個任務。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
     * 從任務佇列取出一個方法
     *
     * @return
     */
    private Runnable getTask()
    {
        if (mType == Type.FIFO)
        {
            return mTaskQueue.removeFirst();
        } else if (mType == Type.LIFO)
        {
            return mTaskQueue.removeLast();
        }
        return null;
    }

getTask程式碼也比較簡單,就是根據Type從任務佇列頭或者尾進行取任務。 

現在你會不會好奇,任務裡面到底什麼程式碼?其實我們也就剩最後一段程式碼了buildTask 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
     * 根據傳入的引數,新建一個任務
     *
     * @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())// 如果在快取檔案中發現
                    {
                        Log.e(TAG, find image : + path +  in disk cache .);
                        bm = loadImageFromLocal(file.getAbsolutePath(),
                                imageView);
                    } else
                    {
                        if (isDiskCacheEnable)// 檢測是否開啟硬碟快取
                        {
                            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
                        // 直接從網路載入
                        {
                            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;
    }

我們新建任務,說明在記憶體中沒有找到快取的bitmap;我們的任務就是去根據path載入壓縮後的bitmap返回即可,然後加入LruCache,設定回撥顯示。 

首先我們判斷是否是網路任務?

如果是,首先去硬碟快取中找一下,(硬碟中檔名為:根據path生成的md5為名稱)。

如果硬碟快取中沒有,那麼去判斷是否開啟了硬碟快取:

開啟了的話:下載圖片,使用loadImageFromLocal本地載入圖片的方式進行載入(壓縮的程式碼前面已經詳細說過);

如果沒有開啟:則直接從網路獲取(壓縮獲取的程式碼,前面詳細說過);

如果不是網路圖片:直接loadImageFromLocal本地載入圖片的方式進行載入 

經過上面,就獲得了bitmap;然後加入addBitmapToLruCache,refreashBitmap回撥顯示圖片。 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
     * 將圖片加入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/專案packageName/cache中:

載入中...

不過有些地方需要注意:就是在程式碼中,你會看到一些訊號量的身影:

第一個:mSemaphorePoolThreadHandler = new Semaphore(0); 用於控制我們的mPoolThreadHandler的初始化完成,我們在使用mPoolThreadHandler會進行判空,如果為null,會通過mSemaphorePoolThreadHandler.acquire()進行阻塞;當mPoolThreadHandler初始化結束,我們會呼叫.release();解除阻塞。

第二個:mSemaphoreThreadPool = new Semaphore(threadCount);這個訊號量的數量和我們載入圖片的執行緒個數一致;每取一個任務去執行,我們會讓訊號量減一;每完成一個任務,會讓訊號量+1,再去取任務;目的是什麼呢?為什麼當我們的任務到來時,如果此時在沒有空閒執行緒,任務則一直新增到TaskQueue中,當執行緒完成任務,可以根據策略去TaskQueue中去取任務,只有這樣,我們的LIFO才有意義。

到此,我們的圖片載入框架就結束了,你可以嘗試下載入本地,或者去載入網路大量的圖片,拼一拼載入速度~~~

4、MainActivity

現在是使用的時刻~~

我在MainActivity中,我使用了Fragment,下面我貼下Fragment和佈局檔案的程式碼,具體的,大家自己看程式碼: 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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;
        }
 
    }
 
}
</string>

可以看到我們在getView中,使用mImageLoader.loadImage一行即完成了圖片的載入。

fragment_list_imgs.xml 

?
1
2
3
<gridview android:horizontalspacing="3dp" android:id="@+id/id_gridview" android:layout_height="match_parent" android:layout_width="match_parent" android:numcolumns="3" android:verticalspacing="3dp" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
 
</gridview>

item_fragment_list_imgs.xml 

?
1
2
3
<imageview android:id="@+id/id_img" android:layout_height="120dp" android:layout_width="match_parent" android:scaletype="centerCrop" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
 
</imageview>

相關文章