照片墻這種功能現(xiàn)在應(yīng)該算是挺常見了汗唱,在很多應(yīng)用中你都可以經(jīng)常看到照片墻的身影丈攒。它的設(shè)計(jì)思路其實(shí)也非常簡(jiǎn)單哩罪,用一個(gè)GridView控件當(dāng)作“墻”,然后隨著GridView的滾動(dòng)將一張張照片貼在“墻”上巡验,這些照片可以是手機(jī)本地中存儲(chǔ)的际插,也可以是從網(wǎng)上下載的。制作類似于這種的功能的應(yīng)用深碱,有一個(gè)非常重要的問題需要考慮腹鹉,就是圖片資源何時(shí)應(yīng)該釋放。因?yàn)殡S著GridView的滾動(dòng)敷硅,加載的圖片可能會(huì)越來(lái)越多,如果沒有一種合理的機(jī)制對(duì)圖片進(jìn)行釋放愉阎,那么當(dāng)圖片達(dá)到一定上限時(shí)绞蹦,程序就必然會(huì)崩潰。
今天我們照片墻應(yīng)用的實(shí)現(xiàn)榜旦,重點(diǎn)也是放在了如何防止由于圖片過(guò)多導(dǎo)致程序崩潰上面幽七。主要的核心算法使用了Android中提供的LruCache類,這個(gè)類是3.1版本中提供的溅呢,如果你是在更早的Android版本中開發(fā)澡屡,則需要導(dǎo)入android-support-v4的jar包。
關(guān)于LruCache用法的詳細(xì)講解咐旧,可以參考
Android高效加載大圖驶鹉、多圖方案,有效避免程序OOM
那我們開始動(dòng)手吧铣墨,新建一個(gè)Android項(xiàng)目室埋,起名叫PhotoWallDemo,這里我使用的是Android 4.0的API。
第一個(gè)要考慮的問題就是姚淆,我們從哪兒去收集這么多的圖片呢孕蝉?這里我從谷歌官方提供的Demo里將圖片源取了出來(lái),我們就從這些網(wǎng)址中下載圖片腌逢,代碼如下所示:
public class Images {
public final static String[] imageThumbUrls = new String[] {
"https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s160-c/A%252520Photographer.jpg",
"https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s160-c/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg",
"https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s160-c/Another%252520Rockaway%252520Sunset.jpg",
"https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s160-c/Antelope%252520Butte.jpg",
"https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s160-c/Antelope%252520Hallway.jpg",
"https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s160-c/Antelope%252520Walls.jpg",
"https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s160-c/Apre%2525CC%252580s%252520la%252520Pluie.jpg",
"https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s160-c/Backlit%252520Cloud.jpg",
"https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s160-c/Bee%252520and%252520Flower.jpg",
"https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s160-c/Bonzai%252520Rock%252520Sunset.jpg",
"https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s160-c/Caterpillar.jpg",
"https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s160-c/Chess.jpg",
"https://lh5.googleusercontent.com/-WVpRptWH8Yw/URqugh-QmDI/AAAAAAAAAbs/E-MgBgtlUWU/s160-c/Chihuly.jpg",
"https://lh5.googleusercontent.com/-0BDXkYmckbo/URquhKFW84I/AAAAAAAAAbs/ogQtHCTk2JQ/s160-c/Closed%252520Door.jpg",
"https://lh3.googleusercontent.com/-PyggXXZRykM/URquh-kVvoI/AAAAAAAAAbs/hFtDwhtrHHQ/s160-c/Colorado%252520River%252520Sunset.jpg",
"https://lh3.googleusercontent.com/-ZAs4dNZtALc/URquikvOCWI/AAAAAAAAAbs/DXz4h3dll1Y/s160-c/Colors%252520of%252520Autumn.jpg",
"https://lh4.googleusercontent.com/-GztnWEIiMz8/URqukVCU7bI/AAAAAAAAAbs/jo2Hjv6MZ6M/s160-c/Countryside.jpg",
"https://lh4.googleusercontent.com/-bEg9EZ9QoiM/URquklz3FGI/AAAAAAAAAbs/UUuv8Ac2BaE/s160-c/Death%252520Valley%252520-%252520Dunes.jpg",
"https://lh6.googleusercontent.com/-ijQJ8W68tEE/URqulGkvFEI/AAAAAAAAAbs/zPXvIwi_rFw/s160-c/Delicate%252520Arch.jpg",
"https://lh5.googleusercontent.com/-Oh8mMy2ieng/URqullDwehI/AAAAAAAAAbs/TbdeEfsaIZY/s160-c/Despair.jpg",
"https://lh5.googleusercontent.com/-gl0y4UiAOlk/URqumC_KjBI/AAAAAAAAAbs/PM1eT7dn4oo/s160-c/Eagle%252520Fall%252520Sunrise.jpg",
"https://lh3.googleusercontent.com/-hYYHd2_vXPQ/URqumtJa9eI/AAAAAAAAAbs/wAalXVkbSh0/s160-c/Electric%252520Storm.jpg",
"https://lh5.googleusercontent.com/-PyY_yiyjPTo/URqunUOhHFI/AAAAAAAAAbs/azZoULNuJXc/s160-c/False%252520Kiva.jpg",
"https://lh6.googleusercontent.com/-PYvLVdvXywk/URqunwd8hfI/AAAAAAAAAbs/qiMwgkFvf6I/s160-c/Fitzgerald%252520Streaks.jpg",
"https://lh4.googleusercontent.com/-KIR_UobIIqY/URquoCZ9SlI/AAAAAAAAAbs/Y4d4q8sXu4c/s160-c/Foggy%252520Sunset.jpg",
"https://lh6.googleusercontent.com/-9lzOk_OWZH0/URquoo4xYoI/AAAAAAAAAbs/AwgzHtNVCwU/s160-c/Frantic.jpg",
"https://lh3.googleusercontent.com/-0X3JNaKaz48/URqupH78wpI/AAAAAAAAAbs/lHXxu_zbH8s/s160-c/Golden%252520Gate%252520Afternoon.jpg",
"https://lh6.googleusercontent.com/-95sb5ag7ABc/URqupl95RDI/AAAAAAAAAbs/g73R20iVTRA/s160-c/Golden%252520Gate%252520Fog.jpg",
"https://lh3.googleusercontent.com/-JB9v6rtgHhk/URqup21F-zI/AAAAAAAAAbs/64Fb8qMZWXk/s160-c/Golden%252520Grass.jpg",
"https://lh4.googleusercontent.com/-EIBGfnuLtII/URquqVHwaRI/AAAAAAAAAbs/FA4McV2u8VE/s160-c/Grand%252520Teton.jpg",
"https://lh4.googleusercontent.com/-WoMxZvmN9nY/URquq1v2AoI/AAAAAAAAAbs/grj5uMhL6NA/s160-c/Grass%252520Closeup.jpg",
"https://lh3.googleusercontent.com/-6hZiEHXx64Q/URqurxvNdqI/AAAAAAAAAbs/kWMXM3o5OVI/s160-c/Green%252520Grass.jpg",
"https://lh5.googleusercontent.com/-6LVb9OXtQ60/URquteBFuKI/AAAAAAAAAbs/4F4kRgecwFs/s160-c/Hanging%252520Leaf.jpg",
"https://lh4.googleusercontent.com/-zAvf__52ONk/URqutT_IuxI/AAAAAAAAAbs/D_bcuc0thoU/s160-c/Highway%2525201.jpg",
"https://lh6.googleusercontent.com/-H4SrUg615rA/URquuL27fXI/AAAAAAAAAbs/4aEqJfiMsOU/s160-c/Horseshoe%252520Bend%252520Sunset.jpg",
"https://lh4.googleusercontent.com/-JhFi4fb_Pqw/URquuX-QXbI/AAAAAAAAAbs/IXpYUxuweYM/s160-c/Horseshoe%252520Bend.jpg",
"https://lh5.googleusercontent.com/-UGgssvFRJ7g/URquueyJzGI/AAAAAAAAAbs/yYIBlLT0toM/s160-c/Into%252520the%252520Blue.jpg",
"https://lh3.googleusercontent.com/-CH7KoupI7uI/URquu0FF__I/AAAAAAAAAbs/R7GDmI7v_G0/s160-c/Jelly%252520Fish%2525202.jpg",
"https://lh4.googleusercontent.com/-pwuuw6yhg8U/URquvPxR3FI/AAAAAAAAAbs/VNGk6f-tsGE/s160-c/Jelly%252520Fish%2525203.jpg",
"https://lh5.googleusercontent.com/-GoUQVw1fnFw/URquv6xbC0I/AAAAAAAAAbs/zEUVTQQ43Zc/s160-c/Kauai.jpg",
"https://lh6.googleusercontent.com/-8QdYYQEpYjw/URquwvdh88I/AAAAAAAAAbs/cktDy-ysfHo/s160-c/Kyoto%252520Sunset.jpg",
"https://lh4.googleusercontent.com/-vPeekyDjOE0/URquwzJ28qI/AAAAAAAAAbs/qxcyXULsZrg/s160-c/Lake%252520Tahoe%252520Colors.jpg",
"https://lh4.googleusercontent.com/-xBPxWpD4yxU/URquxWHk8AI/AAAAAAAAAbs/ARDPeDYPiMY/s160-c/Lava%252520from%252520the%252520Sky.jpg",
"https://lh3.googleusercontent.com/-897VXrJB6RE/URquxxxd-5I/AAAAAAAAAbs/j-Cz4T4YvIw/s160-c/Leica%25252050mm%252520Summilux.jpg",
"https://lh5.googleusercontent.com/-qSJ4D4iXzGo/URquyDWiJ1I/AAAAAAAAAbs/k2pBXeWehOA/s160-c/Leica%25252050mm%252520Summilux.jpg",
"https://lh6.googleusercontent.com/-dwlPg83vzLg/URquylTVuFI/AAAAAAAAAbs/G6SyQ8b4YsI/s160-c/Leica%252520M8%252520%252528Front%252529.jpg",
"https://lh3.googleusercontent.com/-R3_EYAyJvfk/URquzQBv8eI/AAAAAAAAAbs/b9xhpUM3pEI/s160-c/Light%252520to%252520Sand.jpg",
"https://lh3.googleusercontent.com/-fHY5h67QPi0/URqu0Cp4J1I/AAAAAAAAAbs/0lG6m94Z6vM/s160-c/Little%252520Bit%252520of%252520Paradise.jpg",
"https://lh5.googleusercontent.com/-TzF_LwrCnRM/URqu0RddPOI/AAAAAAAAAbs/gaj2dLiuX0s/s160-c/Lone%252520Pine%252520Sunset.jpg",
"https://lh3.googleusercontent.com/-4HdpJ4_DXU4/URqu046dJ9I/AAAAAAAAAbs/eBOodtk2_uk/s160-c/Lonely%252520Rock.jpg",
"https://lh6.googleusercontent.com/-erbF--z-W4s/URqu1ajSLkI/AAAAAAAAAbs/xjDCDO1INzM/s160-c/Longue%252520Vue.jpg",
"https://lh6.googleusercontent.com/-0CXJRdJaqvc/URqu1opNZNI/AAAAAAAAAbs/PFB2oPUU7Lk/s160-c/Look%252520Me%252520in%252520the%252520Eye.jpg",
"https://lh3.googleusercontent.com/-D_5lNxnDN6g/URqu2Tk7HVI/AAAAAAAAAbs/p0ddca9W__Y/s160-c/Lost%252520in%252520a%252520Field.jpg",
"https://lh6.googleusercontent.com/-flsqwMrIk2Q/URqu24PcmjI/AAAAAAAAAbs/5ocIH85XofM/s160-c/Marshall%252520Beach%252520Sunset.jpg",
"https://lh4.googleusercontent.com/-Y4lgryEVTmU/URqu28kG3gI/AAAAAAAAAbs/OjXpekqtbJ4/s160-c/Mono%252520Lake%252520Blue.jpg",
"https://lh4.googleusercontent.com/-AaHAJPmcGYA/URqu3PIldHI/AAAAAAAAAbs/lcTqk1SIcRs/s160-c/Monument%252520Valley%252520Overlook.jpg",
"https://lh4.googleusercontent.com/-vKxfdQ83dQA/URqu31Yq_BI/AAAAAAAAAbs/OUoGk_2AyfM/s160-c/Moving%252520Rock.jpg",
"https://lh5.googleusercontent.com/-CG62QiPpWXg/URqu4ia4vRI/AAAAAAAAAbs/0YOdqLAlcAc/s160-c/Napali%252520Coast.jpg",
"https://lh6.googleusercontent.com/-wdGrP5PMmJQ/URqu5PZvn7I/AAAAAAAAAbs/m0abEcdPXe4/s160-c/One%252520Wheel.jpg",
"https://lh6.googleusercontent.com/-6WS5DoCGuOA/URqu5qx1UgI/AAAAAAAAAbs/giMw2ixPvrY/s160-c/Open%252520Sky.jpg",
"https://lh6.googleusercontent.com/-u8EHKj8G8GQ/URqu55sM6yI/AAAAAAAAAbs/lIXX_GlTdmI/s160-c/Orange%252520Sunset.jpg",
"https://lh6.googleusercontent.com/-74Z5qj4bTDE/URqu6LSrJrI/AAAAAAAAAbs/XzmVkw90szQ/s160-c/Orchid.jpg",
"https://lh6.googleusercontent.com/-lEQE4h6TePE/URqu6t_lSkI/AAAAAAAAAbs/zvGYKOea_qY/s160-c/Over%252520there.jpg",
"https://lh5.googleusercontent.com/-cauH-53JH2M/URqu66v_USI/AAAAAAAAAbs/EucwwqclfKQ/s160-c/Plumes.jpg",
"https://lh3.googleusercontent.com/-eDLT2jHDoy4/URqu7axzkAI/AAAAAAAAAbs/iVZE-xJ7lZs/s160-c/Rainbokeh.jpg",
"https://lh5.googleusercontent.com/-j1NLqEFIyco/URqu8L1CGcI/AAAAAAAAAbs/aqZkgX66zlI/s160-c/Rainbow.jpg",
"https://lh5.googleusercontent.com/-DRnqmK0t4VU/URqu8XYN9yI/AAAAAAAAAbs/LgvF_592WLU/s160-c/Rice%252520Fields.jpg",
"https://lh3.googleusercontent.com/-hwh1v3EOGcQ/URqu8qOaKwI/AAAAAAAAAbs/IljRJRnbJGw/s160-c/Rockaway%252520Fire%252520Sky.jpg",
"https://lh5.googleusercontent.com/-wjV6FQk7tlk/URqu9jCQ8sI/AAAAAAAAAbs/RyYUpdo-c9o/s160-c/Rockaway%252520Flow.jpg",
"https://lh6.googleusercontent.com/-6cAXNfo7D20/URqu-BdzgPI/AAAAAAAAAbs/OmsYllzJqwo/s160-c/Rockaway%252520Sunset%252520Sky.jpg",
"https://lh3.googleusercontent.com/-sl8fpGPS-RE/URqu_BOkfgI/AAAAAAAAAbs/Dg2Fv-JxOeg/s160-c/Russian%252520Ridge%252520Sunset.jpg",
"https://lh6.googleusercontent.com/-gVtY36mMBIg/URqu_q91lkI/AAAAAAAAAbs/3CiFMBcy5MA/s160-c/Rust%252520Knot.jpg",
"https://lh6.googleusercontent.com/-GHeImuHqJBE/URqu_FKfVLI/AAAAAAAAAbs/axuEJeqam7Q/s160-c/Sailing%252520Stones.jpg",
"https://lh3.googleusercontent.com/-hBbYZjTOwGc/URqu_ycpIrI/AAAAAAAAAbs/nAdJUXnGJYE/s160-c/Seahorse.jpg",
"https://lh3.googleusercontent.com/-Iwi6-i6IexY/URqvAYZHsVI/AAAAAAAAAbs/5ETWl4qXsFE/s160-c/Shinjuku%252520Street.jpg",
"https://lh6.googleusercontent.com/-amhnySTM_MY/URqvAlb5KoI/AAAAAAAAAbs/pFCFgzlKsn0/s160-c/Sierra%252520Heavens.jpg",
"https://lh5.googleusercontent.com/-dJgjepFrYSo/URqvBVJZrAI/AAAAAAAAAbs/v-F5QWpYO6s/s160-c/Sierra%252520Sunset.jpg",
"https://lh4.googleusercontent.com/-Z4zGiC5nWdc/URqvBdEwivI/AAAAAAAAAbs/ZRZR1VJ84QA/s160-c/Sin%252520Lights.jpg",
"https://lh4.googleusercontent.com/-_0cYiWW8ccY/URqvBz3iM4I/AAAAAAAAAbs/9N_Wq8MhLTY/s160-c/Starry%252520Lake.jpg",
"https://lh3.googleusercontent.com/-A9LMoRyuQUA/URqvCYx_JoI/AAAAAAAAAbs/s7sde1Bz9cI/s160-c/Starry%252520Night.jpg",
"https://lh3.googleusercontent.com/-KtLJ3k858eY/URqvC_2h_bI/AAAAAAAAAbs/zzEBImwDA_g/s160-c/Stream.jpg",
"https://lh5.googleusercontent.com/-dFB7Lad6RcA/URqvDUftwWI/AAAAAAAAAbs/BrhoUtXTN7o/s160-c/Strip%252520Sunset.jpg",
"https://lh5.googleusercontent.com/-at6apgFiN20/URqvDyffUZI/AAAAAAAAAbs/clABCx171bE/s160-c/Sunset%252520Hills.jpg",
"https://lh4.googleusercontent.com/-7-EHhtQthII/URqvEYTk4vI/AAAAAAAAAbs/QSJZoB3YjVg/s160-c/Tenaya%252520Lake%2525202.jpg",
"https://lh6.googleusercontent.com/-8MrjV_a-Pok/URqvFC5repI/AAAAAAAAAbs/9inKTg9fbCE/s160-c/Tenaya%252520Lake.jpg",
"https://lh5.googleusercontent.com/-B1HW-z4zwao/URqvFWYRwUI/AAAAAAAAAbs/8Peli53Bs8I/s160-c/The%252520Cave%252520BW.jpg",
"https://lh3.googleusercontent.com/-PO4E-xZKAnQ/URqvGRqjYkI/AAAAAAAAAbs/42nyADFsXag/s160-c/The%252520Fisherman.jpg",
"https://lh4.googleusercontent.com/-iLyZlzfdy7s/URqvG0YScdI/AAAAAAAAAbs/1J9eDKmkXtk/s160-c/The%252520Night%252520is%252520Coming.jpg",
"https://lh6.googleusercontent.com/-G-k7YkkUco0/URqvHhah6fI/AAAAAAAAAbs/_taQQG7t0vo/s160-c/The%252520Road.jpg",
"https://lh6.googleusercontent.com/-h-ALJt7kSus/URqvIThqYfI/AAAAAAAAAbs/ejiv35olWS8/s160-c/Tokyo%252520Heights.jpg",
"https://lh5.googleusercontent.com/-Hy9k-TbS7xg/URqvIjQMOxI/AAAAAAAAAbs/RSpmmOATSkg/s160-c/Tokyo%252520Highway.jpg",
"https://lh6.googleusercontent.com/-83oOvMb4OZs/URqvJL0T7lI/AAAAAAAAAbs/c5TECZ6RONM/s160-c/Tokyo%252520Smog.jpg",
"https://lh3.googleusercontent.com/-FB-jfgREEfI/URqvJI3EXAI/AAAAAAAAAbs/XfyweiRF4v8/s160-c/Tufa%252520at%252520Night.jpg",
"https://lh4.googleusercontent.com/-vngKD5Z1U8w/URqvJUCEgPI/AAAAAAAAAbs/ulxCMVcU6EU/s160-c/Valley%252520Sunset.jpg",
"https://lh6.googleusercontent.com/-DOz5I2E2oMQ/URqvKMND1kI/AAAAAAAAAbs/Iqf0IsInleo/s160-c/Windmill%252520Sunrise.jpg",
"https://lh5.googleusercontent.com/-biyiyWcJ9MU/URqvKculiAI/AAAAAAAAAbs/jyPsCplJOpE/s160-c/Windmill.jpg",
"https://lh4.googleusercontent.com/-PDT167_xRdA/URqvK36mLcI/AAAAAAAAAbs/oi2ik9QseMI/s160-c/Windmills.jpg",
"https://lh5.googleusercontent.com/-kI_QdYx7VlU/URqvLXCB6gI/AAAAAAAAAbs/N31vlZ6u89o/s160-c/Yet%252520Another%252520Rockaway%252520Sunset.jpg",
"https://lh4.googleusercontent.com/-e9NHZ5k5MSs/URqvMIBZjtI/AAAAAAAAAbs/1fV810rDNfQ/s160-c/Yosemite%252520Tree.jpg", };
}
圖片源已經(jīng)有了降淮,現(xiàn)在我們就該考慮在哪里放置這些圖片了。新建或打開activity_main.xml作為程序的主布局搏讶,加入如下代碼:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<GridView
android:id="@+id/photo_wall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="90dip"
android:stretchMode="columnWidth"
android:numColumns="auto_fit"
android:verticalSpacing="10dip"
android:gravity="center"
></GridView>
</LinearLayout>
可以看到佳鳖,我們?cè)谶@個(gè)布局文件中僅加入了一個(gè)GridView,這也就是我們程序中的“墻”窍蓝,所有的圖片都將貼在這個(gè)“墻”上腋颠。
接著我們定義GridView中每一個(gè)子View的布局,新建一個(gè)photo_layout.xml布局吓笙,加入如下代碼:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/photo"
android:layout_width="90dip"
android:layout_height="90dip"
android:src="@drawable/empty_photo"
android:layout_centerInParent="true"
/>
</RelativeLayout>
在每一個(gè)子View中我們就簡(jiǎn)單使用了一個(gè)ImageView來(lái)顯示一張圖片淑玫。這樣所有的布局就已經(jīng)定義好了。
接下來(lái)新建PhotoWallAdapter做為GridView的適配器面睛,代碼如下所示:
public class PhotoWallAdapter extends ArrayAdapter<String> implements OnScrollListener {
/**
* 記錄所有正在下載或等待下載的任務(wù)絮蒿。
*/
private Set<BitmapWorkerTask> taskCollection;
/**
* 圖片緩存技術(shù)的核心類,用于緩存所有下載好的圖片叁鉴,在程序內(nèi)存達(dá)到設(shè)定值時(shí)會(huì)將最少最近使用的圖片移除掉土涝。
*/
private LruCache<String, Bitmap> mMemoryCache;
/**
* GridView的實(shí)例
*/
private GridView mPhotoWall;
/**
* 第一張可見圖片的下標(biāo)
*/
private int mFirstVisibleItem;
/**
* 一屏有多少?gòu)垐D片可見
*/
private int mVisibleItemCount;
/**
* 記錄是否剛打開程序,用于解決進(jìn)入程序不滾動(dòng)屏幕幌墓,不會(huì)下載圖片的問題但壮。
*/
private boolean isFirstEnter = true;
public PhotoWallAdapter(Context context, int textViewResourceId, String[] objects,
GridView photoWall) {
super(context, textViewResourceId, objects);
mPhotoWall = photoWall;
taskCollection = new HashSet<BitmapWorkerTask>();
// 獲取應(yīng)用程序最大可用內(nèi)存
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemory / 8;
// 設(shè)置圖片緩存大小為程序最大可用內(nèi)存的1/8
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount();
}
};
mPhotoWall.setOnScrollListener(this);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final String url = getItem(position);
View view;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.photo_layout, null);
} else {
view = convertView;
}
final ImageView photo = (ImageView) view.findViewById(R.id.photo);
// 給ImageView設(shè)置一個(gè)Tag,保證異步加載圖片時(shí)不會(huì)亂序
photo.setTag(url);
setImageView(url, photo);
return view;
}
/**
* 給ImageView設(shè)置圖片常侣。首先從LruCache中取出圖片的緩存蜡饵,設(shè)置到ImageView上。如果LruCache中沒有該圖片的緩存胳施,
* 就給ImageView設(shè)置一張默認(rèn)圖片溯祸。
*
* @param imageUrl
* 圖片的URL地址,用于作為L(zhǎng)ruCache的鍵舞肆。
* @param imageView
* 用于顯示圖片的控件焦辅。
*/
private void setImageView(String imageUrl, ImageView imageView) {
Bitmap bitmap = getBitmapFromMemoryCache(imageUrl);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageResource(R.drawable.empty_photo);
}
}
/**
* 將一張圖片存儲(chǔ)到LruCache中。
*
* @param key
* LruCache的鍵椿胯,這里傳入圖片的URL地址筷登。
* @param bitmap
* LruCache的鍵,這里傳入從網(wǎng)絡(luò)上下載的Bitmap對(duì)象压状。
*/
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemoryCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
/**
* 從LruCache中獲取一張圖片仆抵,如果不存在就返回null跟继。
*
* @param key
* LruCache的鍵,這里傳入圖片的URL地址镣丑。
* @return 對(duì)應(yīng)傳入鍵的Bitmap對(duì)象舔糖,或者null。
*/
public Bitmap getBitmapFromMemoryCache(String key) {
return mMemoryCache.get(key);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// 僅當(dāng)GridView靜止時(shí)才去下載圖片莺匠,GridView滑動(dòng)時(shí)取消所有正在下載的任務(wù)
if (scrollState == SCROLL_STATE_IDLE) {
loadBitmaps(mFirstVisibleItem, mVisibleItemCount);
} else {
cancelAllTasks();
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
mFirstVisibleItem = firstVisibleItem;
mVisibleItemCount = visibleItemCount;
// 下載的任務(wù)應(yīng)該由onScrollStateChanged里調(diào)用金吗,但首次進(jìn)入程序時(shí)onScrollStateChanged并不會(huì)調(diào)用,
// 因此在這里為首次進(jìn)入程序開啟下載任務(wù)趣竣。
if (isFirstEnter && visibleItemCount > 0) {
loadBitmaps(firstVisibleItem, visibleItemCount);
isFirstEnter = false;
}
}
/**
* 加載Bitmap對(duì)象摇庙。此方法會(huì)在LruCache中檢查所有屏幕中可見的ImageView的Bitmap對(duì)象,
* 如果發(fā)現(xiàn)任何一個(gè)ImageView的Bitmap對(duì)象不在緩存中遥缕,就會(huì)開啟異步線程去下載圖片卫袒。
*
* @param firstVisibleItem
* 第一個(gè)可見的ImageView的下標(biāo)
* @param visibleItemCount
* 屏幕中總共可見的元素?cái)?shù)
*/
private void loadBitmaps(int firstVisibleItem, int visibleItemCount) {
try {
for (int i = firstVisibleItem; i < firstVisibleItem + visibleItemCount; i++) {
String imageUrl = Images.imageThumbUrls[i];
Bitmap bitmap = getBitmapFromMemoryCache(imageUrl);
if (bitmap == null) {
BitmapWorkerTask task = new BitmapWorkerTask();
taskCollection.add(task);
task.execute(imageUrl);
} else {
ImageView imageView = (ImageView) mPhotoWall.findViewWithTag(imageUrl);
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 取消所有正在下載或等待下載的任務(wù)。
*/
public void cancelAllTasks() {
if (taskCollection != null) {
for (BitmapWorkerTask task : taskCollection) {
task.cancel(false);
}
}
}
/**
* 異步下載圖片的任務(wù)单匣。
*
* @author guolin
*/
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
/**
* 圖片的URL地址
*/
private String imageUrl;
@Override
protected Bitmap doInBackground(String... params) {
imageUrl = params[0];
// 在后臺(tái)開始下載圖片
Bitmap bitmap = downloadBitmap(params[0]);
if (bitmap != null) {
// 圖片下載完成后緩存到LrcCache中
addBitmapToMemoryCache(params[0], bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
// 根據(jù)Tag找到相應(yīng)的ImageView控件夕凝,將下載好的圖片顯示出來(lái)。
ImageView imageView = (ImageView) mPhotoWall.findViewWithTag(imageUrl);
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
}
taskCollection.remove(this);
}
/**
* 建立HTTP請(qǐng)求户秤,并獲取Bitmap對(duì)象码秉。
*
* @param imageUrl
* 圖片的URL地址
* @return 解析后的Bitmap對(duì)象
*/
private Bitmap downloadBitmap(String imageUrl) {
Bitmap bitmap = null;
HttpURLConnection con = null;
try {
URL url = new URL(imageUrl);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(10 * 1000);
bitmap = BitmapFactory.decodeStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}
return bitmap;
}
}
}
PhotoWallAdapter是整個(gè)照片墻程序中最關(guān)鍵的一個(gè)類了,這里我來(lái)重點(diǎn)給大家講解一下鸡号。首先在PhotoWallAdapter的構(gòu)造函數(shù)中转砖,我們初始化了LruCache類,并設(shè)置了最大緩存容量為程序最大可用內(nèi)存的1/8鲸伴,接下來(lái)又為GridView注冊(cè)了一個(gè)滾動(dòng)監(jiān)聽器府蔗。然后在getView()方法中,我們?yōu)槊總€(gè)ImageView設(shè)置了一個(gè)唯一的Tag汞窗,這個(gè)Tag的作用是為了后面能夠準(zhǔn)確地找回這個(gè)ImageView礁竞,不然異步加載圖片會(huì)出現(xiàn)亂序的情況。之后調(diào)用了setImageView()方法為ImageView設(shè)置一張圖片杉辙,這個(gè)方法首先會(huì)從LruCache緩存中查找是否已經(jīng)緩存了這張圖片,如果成功找到則將緩存中的圖片顯示在ImageView上捶朵,否則就顯示一張默認(rèn)的空?qǐng)D片蜘矢。
看了半天,那到底是在哪里下載圖片的呢综看?這是在GridView的滾動(dòng)監(jiān)聽器中進(jìn)行的品腹,在onScrollStateChanged()方法中,我們對(duì)GridView的滾動(dòng)狀態(tài)進(jìn)行了判斷红碑,如果當(dāng)前GridView是靜止的舞吭,則調(diào)用loadBitmaps()方法去下載圖片泡垃,如果GridView正在滾動(dòng),則取消掉所有下載任務(wù)羡鸥,這樣可以保證GridView滾動(dòng)的流暢性蔑穴。在loadBitmaps()方法中,我們?yōu)槠聊簧纤锌梢姷腉ridView子元素開啟了一個(gè)線程去執(zhí)行下載任務(wù)惧浴,下載成功后將圖片存儲(chǔ)到LruCache當(dāng)中存和,然后通過(guò)Tag找到相應(yīng)的ImageView控件,把下載好的圖片顯示出來(lái)衷旅。
由于我們使用了LruCache來(lái)緩存圖片捐腿,所以不需要擔(dān)心內(nèi)存溢出的情況,當(dāng)LruCache中存儲(chǔ)圖片的總大小達(dá)到容量上限的時(shí)候柿顶,會(huì)自動(dòng)把最近最少使用的圖片從緩存中移除茄袖。
最后新建或打開MainActivity作為程序的主Activity,代碼如下所示:
public class MainActivity extends Activity {
/**
* 用于展示照片墻的GridView
*/
private GridView mPhotoWall;
/**
* GridView的適配器
*/
private PhotoWallAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPhotoWall = (GridView) findViewById(R.id.photo_wall);
adapter = new PhotoWallAdapter(this, 0, Images.imageThumbUrls, mPhotoWall);
mPhotoWall.setAdapter(adapter);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 退出程序時(shí)結(jié)束所有的下載任務(wù)
adapter.cancelAllTasks();
}
}
MainActivity中的代碼非常簡(jiǎn)單嘁锯,沒什么需要說(shuō)明的了宪祥,在Activity被銷毀時(shí)取消掉了所有的下載任務(wù),避免程序在后臺(tái)耗費(fèi)流量猪钮。另外由于我們使用了網(wǎng)絡(luò)功能品山,別忘了在AndroidManifest.xml中加入網(wǎng)絡(luò)權(quán)限的聲明。
現(xiàn)在可以運(yùn)行一下程序了烤低,效果如下圖所示:
可以看到肘交,滾動(dòng)照片墻,會(huì)異步加載圖片到相應(yīng)的ImageView上扑馁。隨著加載圖片的增多涯呻,會(huì)釋放掉一些之前加載過(guò)的圖片,你多滾動(dòng)幾次就可以看得出了腻要。另外為了能讓大家明顯看出圖片的釋放情況复罐,我在這個(gè)程序中沒有使用本地緩存,所有被釋放掉的圖片再次顯示需要從網(wǎng)絡(luò)上再下載一遍雄家。在實(shí)際的項(xiàng)目中配合適當(dāng)?shù)谋镜鼐彺嫘Ч麜?huì)更好效诅。
打開DDMS,我們可以發(fā)現(xiàn)趟济,由于有LruCache幫我們管理圖片緩存乱投,不管如何滾動(dòng)照片墻,程序內(nèi)存始終會(huì)保持在一個(gè)合理的范圍內(nèi)顷编。
本篇文章的重點(diǎn)在于如何對(duì)圖片進(jìn)行更好的回收戚炫,因此照片墻只是簡(jiǎn)單地使用GridView進(jìn)行了展示,想要看更酷更炫的照片墻效果的朋友媳纬,可以參考我后面的一篇文章
Android瀑布流照片墻實(shí)現(xiàn)双肤,體驗(yàn)不規(guī)則排列的美感
好了施掏,今天的講解到此結(jié)束,有疑問的朋友請(qǐng)?jiān)谙旅媪粞浴?/p>