Android照片牆應用實現,再多的圖片也不怕崩潰

轉載請註明出處:http://blog.csdn.net/guolin_blog/article/details/9526203html

照片牆這種功能如今應該算是挺常見了,在不少應用中你均可以常常看到照片牆的身影。它的設計思路其實也很是簡單,用一個GridView控件看成「牆」,而後隨着GridView的滾動將一張張照片貼在「牆」上,這些照片能夠是手機本地中存儲的,也能夠是從網上下載的。製做相似於這種的功能的應用,有一個很是重要的問題須要考慮,就是圖片資源什麼時候應該釋放。由於隨着GridView的滾動,加載的圖片可能會愈來愈多,若是沒有一種合理的機制對圖片進行釋放,那麼當圖片達到必定上限時,程序就必然會崩潰。
java

今天咱們照片牆應用的實現,重點也是放在瞭如何防止因爲圖片過多致使程序崩潰上面。主要的核心算法使用了Android中提供的LruCache類,這個類是3.1版本中提供的,若是你是在更早的Android版本中開發,則須要導入android-support-v4的jar包。android

關於LruCache用法的詳細講解,能夠參考Android高效加載大圖、多圖方案,有效避免程序OOM算法

那咱們開始動手吧,新建一個Android項目,起名叫PhotoWallDemo,這裏我使用的是Android 4.0的API。緩存

第一個要考慮的問題就是,咱們從哪兒去收集這麼多的圖片呢?這裏我從谷歌官方提供的Demo裏將圖片源取了出來,咱們就從這些網址中下載圖片,代碼以下所示:網絡

[java] view plaincopyapp

  1. public class Images {  異步

  2.   

  3.     public final static String[] imageThumbUrls = new String[] {  ide

  4.             "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s160-c/A%252520Photographer.jpg",  函數

  5.             "https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s160-c/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg",  

  6.             "https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s160-c/Another%252520Rockaway%252520Sunset.jpg",  

  7.             "https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s160-c/Antelope%252520Butte.jpg",  

  8.             "https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s160-c/Antelope%252520Hallway.jpg",  

  9.             "https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s160-c/Antelope%252520Walls.jpg",  

  10.             "https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s160-c/Apre%2525CC%252580s%252520la%252520Pluie.jpg",  

  11.             "https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s160-c/Backlit%252520Cloud.jpg",  

  12.             "https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s160-c/Bee%252520and%252520Flower.jpg",  

  13.             "https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s160-c/Bonzai%252520Rock%252520Sunset.jpg",  

  14.             "https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s160-c/Caterpillar.jpg",  

  15.             "https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s160-c/Chess.jpg",  

  16.             "https://lh5.googleusercontent.com/-WVpRptWH8Yw/URqugh-QmDI/AAAAAAAAAbs/E-MgBgtlUWU/s160-c/Chihuly.jpg",  

  17.             "https://lh5.googleusercontent.com/-0BDXkYmckbo/URquhKFW84I/AAAAAAAAAbs/ogQtHCTk2JQ/s160-c/Closed%252520Door.jpg",  

  18.             "https://lh3.googleusercontent.com/-PyggXXZRykM/URquh-kVvoI/AAAAAAAAAbs/hFtDwhtrHHQ/s160-c/Colorado%252520River%252520Sunset.jpg",  

  19.             "https://lh3.googleusercontent.com/-ZAs4dNZtALc/URquikvOCWI/AAAAAAAAAbs/DXz4h3dll1Y/s160-c/Colors%252520of%252520Autumn.jpg",  

  20.             "https://lh4.googleusercontent.com/-GztnWEIiMz8/URqukVCU7bI/AAAAAAAAAbs/jo2Hjv6MZ6M/s160-c/Countryside.jpg",  

  21.             "https://lh4.googleusercontent.com/-bEg9EZ9QoiM/URquklz3FGI/AAAAAAAAAbs/UUuv8Ac2BaE/s160-c/Death%252520Valley%252520-%252520Dunes.jpg",  

  22.             "https://lh6.googleusercontent.com/-ijQJ8W68tEE/URqulGkvFEI/AAAAAAAAAbs/zPXvIwi_rFw/s160-c/Delicate%252520Arch.jpg",  

  23.             "https://lh5.googleusercontent.com/-Oh8mMy2ieng/URqullDwehI/AAAAAAAAAbs/TbdeEfsaIZY/s160-c/Despair.jpg",  

  24.             "https://lh5.googleusercontent.com/-gl0y4UiAOlk/URqumC_KjBI/AAAAAAAAAbs/PM1eT7dn4oo/s160-c/Eagle%252520Fall%252520Sunrise.jpg",  

  25.             "https://lh3.googleusercontent.com/-hYYHd2_vXPQ/URqumtJa9eI/AAAAAAAAAbs/wAalXVkbSh0/s160-c/Electric%252520Storm.jpg",  

  26.             "https://lh5.googleusercontent.com/-PyY_yiyjPTo/URqunUOhHFI/AAAAAAAAAbs/azZoULNuJXc/s160-c/False%252520Kiva.jpg",  

  27.             "https://lh6.googleusercontent.com/-PYvLVdvXywk/URqunwd8hfI/AAAAAAAAAbs/qiMwgkFvf6I/s160-c/Fitzgerald%252520Streaks.jpg",  

  28.             "https://lh4.googleusercontent.com/-KIR_UobIIqY/URquoCZ9SlI/AAAAAAAAAbs/Y4d4q8sXu4c/s160-c/Foggy%252520Sunset.jpg",  

  29.             "https://lh6.googleusercontent.com/-9lzOk_OWZH0/URquoo4xYoI/AAAAAAAAAbs/AwgzHtNVCwU/s160-c/Frantic.jpg",  

  30.             "https://lh3.googleusercontent.com/-0X3JNaKaz48/URqupH78wpI/AAAAAAAAAbs/lHXxu_zbH8s/s160-c/Golden%252520Gate%252520Afternoon.jpg",  

  31.             "https://lh6.googleusercontent.com/-95sb5ag7ABc/URqupl95RDI/AAAAAAAAAbs/g73R20iVTRA/s160-c/Golden%252520Gate%252520Fog.jpg",  

  32.             "https://lh3.googleusercontent.com/-JB9v6rtgHhk/URqup21F-zI/AAAAAAAAAbs/64Fb8qMZWXk/s160-c/Golden%252520Grass.jpg",  

  33.             "https://lh4.googleusercontent.com/-EIBGfnuLtII/URquqVHwaRI/AAAAAAAAAbs/FA4McV2u8VE/s160-c/Grand%252520Teton.jpg",  

  34.             "https://lh4.googleusercontent.com/-WoMxZvmN9nY/URquq1v2AoI/AAAAAAAAAbs/grj5uMhL6NA/s160-c/Grass%252520Closeup.jpg",  

  35.             "https://lh3.googleusercontent.com/-6hZiEHXx64Q/URqurxvNdqI/AAAAAAAAAbs/kWMXM3o5OVI/s160-c/Green%252520Grass.jpg",  

  36.             "https://lh5.googleusercontent.com/-6LVb9OXtQ60/URquteBFuKI/AAAAAAAAAbs/4F4kRgecwFs/s160-c/Hanging%252520Leaf.jpg",  

  37.             "https://lh4.googleusercontent.com/-zAvf__52ONk/URqutT_IuxI/AAAAAAAAAbs/D_bcuc0thoU/s160-c/Highway%2525201.jpg",  

  38.             "https://lh6.googleusercontent.com/-H4SrUg615rA/URquuL27fXI/AAAAAAAAAbs/4aEqJfiMsOU/s160-c/Horseshoe%252520Bend%252520Sunset.jpg",  

  39.             "https://lh4.googleusercontent.com/-JhFi4fb_Pqw/URquuX-QXbI/AAAAAAAAAbs/IXpYUxuweYM/s160-c/Horseshoe%252520Bend.jpg",  

  40.             "https://lh5.googleusercontent.com/-UGgssvFRJ7g/URquueyJzGI/AAAAAAAAAbs/yYIBlLT0toM/s160-c/Into%252520the%252520Blue.jpg",  

  41.             "https://lh3.googleusercontent.com/-CH7KoupI7uI/URquu0FF__I/AAAAAAAAAbs/R7GDmI7v_G0/s160-c/Jelly%252520Fish%2525202.jpg",  

  42.             "https://lh4.googleusercontent.com/-pwuuw6yhg8U/URquvPxR3FI/AAAAAAAAAbs/VNGk6f-tsGE/s160-c/Jelly%252520Fish%2525203.jpg",  

  43.             "https://lh5.googleusercontent.com/-GoUQVw1fnFw/URquv6xbC0I/AAAAAAAAAbs/zEUVTQQ43Zc/s160-c/Kauai.jpg",  

  44.             "https://lh6.googleusercontent.com/-8QdYYQEpYjw/URquwvdh88I/AAAAAAAAAbs/cktDy-ysfHo/s160-c/Kyoto%252520Sunset.jpg",  

  45.             "https://lh4.googleusercontent.com/-vPeekyDjOE0/URquwzJ28qI/AAAAAAAAAbs/qxcyXULsZrg/s160-c/Lake%252520Tahoe%252520Colors.jpg",  

  46.             "https://lh4.googleusercontent.com/-xBPxWpD4yxU/URquxWHk8AI/AAAAAAAAAbs/ARDPeDYPiMY/s160-c/Lava%252520from%252520the%252520Sky.jpg",  

  47.             "https://lh3.googleusercontent.com/-897VXrJB6RE/URquxxxd-5I/AAAAAAAAAbs/j-Cz4T4YvIw/s160-c/Leica%25252050mm%252520Summilux.jpg",  

  48.             "https://lh5.googleusercontent.com/-qSJ4D4iXzGo/URquyDWiJ1I/AAAAAAAAAbs/k2pBXeWehOA/s160-c/Leica%25252050mm%252520Summilux.jpg",  

  49.             "https://lh6.googleusercontent.com/-dwlPg83vzLg/URquylTVuFI/AAAAAAAAAbs/G6SyQ8b4YsI/s160-c/Leica%252520M8%252520%252528Front%252529.jpg",  

  50.             "https://lh3.googleusercontent.com/-R3_EYAyJvfk/URquzQBv8eI/AAAAAAAAAbs/b9xhpUM3pEI/s160-c/Light%252520to%252520Sand.jpg",  

  51.             "https://lh3.googleusercontent.com/-fHY5h67QPi0/URqu0Cp4J1I/AAAAAAAAAbs/0lG6m94Z6vM/s160-c/Little%252520Bit%252520of%252520Paradise.jpg",  

  52.             "https://lh5.googleusercontent.com/-TzF_LwrCnRM/URqu0RddPOI/AAAAAAAAAbs/gaj2dLiuX0s/s160-c/Lone%252520Pine%252520Sunset.jpg",  

  53.             "https://lh3.googleusercontent.com/-4HdpJ4_DXU4/URqu046dJ9I/AAAAAAAAAbs/eBOodtk2_uk/s160-c/Lonely%252520Rock.jpg",  

  54.             "https://lh6.googleusercontent.com/-erbF--z-W4s/URqu1ajSLkI/AAAAAAAAAbs/xjDCDO1INzM/s160-c/Longue%252520Vue.jpg",  

  55.             "https://lh6.googleusercontent.com/-0CXJRdJaqvc/URqu1opNZNI/AAAAAAAAAbs/PFB2oPUU7Lk/s160-c/Look%252520Me%252520in%252520the%252520Eye.jpg",  

  56.             "https://lh3.googleusercontent.com/-D_5lNxnDN6g/URqu2Tk7HVI/AAAAAAAAAbs/p0ddca9W__Y/s160-c/Lost%252520in%252520a%252520Field.jpg",  

  57.             "https://lh6.googleusercontent.com/-flsqwMrIk2Q/URqu24PcmjI/AAAAAAAAAbs/5ocIH85XofM/s160-c/Marshall%252520Beach%252520Sunset.jpg",  

  58.             "https://lh4.googleusercontent.com/-Y4lgryEVTmU/URqu28kG3gI/AAAAAAAAAbs/OjXpekqtbJ4/s160-c/Mono%252520Lake%252520Blue.jpg",  

  59.             "https://lh4.googleusercontent.com/-AaHAJPmcGYA/URqu3PIldHI/AAAAAAAAAbs/lcTqk1SIcRs/s160-c/Monument%252520Valley%252520Overlook.jpg",  

  60.             "https://lh4.googleusercontent.com/-vKxfdQ83dQA/URqu31Yq_BI/AAAAAAAAAbs/OUoGk_2AyfM/s160-c/Moving%252520Rock.jpg",  

  61.             "https://lh5.googleusercontent.com/-CG62QiPpWXg/URqu4ia4vRI/AAAAAAAAAbs/0YOdqLAlcAc/s160-c/Napali%252520Coast.jpg",  

  62.             "https://lh6.googleusercontent.com/-wdGrP5PMmJQ/URqu5PZvn7I/AAAAAAAAAbs/m0abEcdPXe4/s160-c/One%252520Wheel.jpg",  

  63.             "https://lh6.googleusercontent.com/-6WS5DoCGuOA/URqu5qx1UgI/AAAAAAAAAbs/giMw2ixPvrY/s160-c/Open%252520Sky.jpg",  

  64.             "https://lh6.googleusercontent.com/-u8EHKj8G8GQ/URqu55sM6yI/AAAAAAAAAbs/lIXX_GlTdmI/s160-c/Orange%252520Sunset.jpg",  

  65.             "https://lh6.googleusercontent.com/-74Z5qj4bTDE/URqu6LSrJrI/AAAAAAAAAbs/XzmVkw90szQ/s160-c/Orchid.jpg",  

  66.             "https://lh6.googleusercontent.com/-lEQE4h6TePE/URqu6t_lSkI/AAAAAAAAAbs/zvGYKOea_qY/s160-c/Over%252520there.jpg",  

  67.             "https://lh5.googleusercontent.com/-cauH-53JH2M/URqu66v_USI/AAAAAAAAAbs/EucwwqclfKQ/s160-c/Plumes.jpg",  

  68.             "https://lh3.googleusercontent.com/-eDLT2jHDoy4/URqu7axzkAI/AAAAAAAAAbs/iVZE-xJ7lZs/s160-c/Rainbokeh.jpg",  

  69.             "https://lh5.googleusercontent.com/-j1NLqEFIyco/URqu8L1CGcI/AAAAAAAAAbs/aqZkgX66zlI/s160-c/Rainbow.jpg",  

  70.             "https://lh5.googleusercontent.com/-DRnqmK0t4VU/URqu8XYN9yI/AAAAAAAAAbs/LgvF_592WLU/s160-c/Rice%252520Fields.jpg",  

  71.             "https://lh3.googleusercontent.com/-hwh1v3EOGcQ/URqu8qOaKwI/AAAAAAAAAbs/IljRJRnbJGw/s160-c/Rockaway%252520Fire%252520Sky.jpg",  

  72.             "https://lh5.googleusercontent.com/-wjV6FQk7tlk/URqu9jCQ8sI/AAAAAAAAAbs/RyYUpdo-c9o/s160-c/Rockaway%252520Flow.jpg",  

  73.             "https://lh6.googleusercontent.com/-6cAXNfo7D20/URqu-BdzgPI/AAAAAAAAAbs/OmsYllzJqwo/s160-c/Rockaway%252520Sunset%252520Sky.jpg",  

  74.             "https://lh3.googleusercontent.com/-sl8fpGPS-RE/URqu_BOkfgI/AAAAAAAAAbs/Dg2Fv-JxOeg/s160-c/Russian%252520Ridge%252520Sunset.jpg",  

  75.             "https://lh6.googleusercontent.com/-gVtY36mMBIg/URqu_q91lkI/AAAAAAAAAbs/3CiFMBcy5MA/s160-c/Rust%252520Knot.jpg",  

  76.             "https://lh6.googleusercontent.com/-GHeImuHqJBE/URqu_FKfVLI/AAAAAAAAAbs/axuEJeqam7Q/s160-c/Sailing%252520Stones.jpg",  

  77.             "https://lh3.googleusercontent.com/-hBbYZjTOwGc/URqu_ycpIrI/AAAAAAAAAbs/nAdJUXnGJYE/s160-c/Seahorse.jpg",  

  78.             "https://lh3.googleusercontent.com/-Iwi6-i6IexY/URqvAYZHsVI/AAAAAAAAAbs/5ETWl4qXsFE/s160-c/Shinjuku%252520Street.jpg",  

  79.             "https://lh6.googleusercontent.com/-amhnySTM_MY/URqvAlb5KoI/AAAAAAAAAbs/pFCFgzlKsn0/s160-c/Sierra%252520Heavens.jpg",  

  80.             "https://lh5.googleusercontent.com/-dJgjepFrYSo/URqvBVJZrAI/AAAAAAAAAbs/v-F5QWpYO6s/s160-c/Sierra%252520Sunset.jpg",  

  81.             "https://lh4.googleusercontent.com/-Z4zGiC5nWdc/URqvBdEwivI/AAAAAAAAAbs/ZRZR1VJ84QA/s160-c/Sin%252520Lights.jpg",  

  82.             "https://lh4.googleusercontent.com/-_0cYiWW8ccY/URqvBz3iM4I/AAAAAAAAAbs/9N_Wq8MhLTY/s160-c/Starry%252520Lake.jpg",  

  83.             "https://lh3.googleusercontent.com/-A9LMoRyuQUA/URqvCYx_JoI/AAAAAAAAAbs/s7sde1Bz9cI/s160-c/Starry%252520Night.jpg",  

  84.             "https://lh3.googleusercontent.com/-KtLJ3k858eY/URqvC_2h_bI/AAAAAAAAAbs/zzEBImwDA_g/s160-c/Stream.jpg",  

  85.             "https://lh5.googleusercontent.com/-dFB7Lad6RcA/URqvDUftwWI/AAAAAAAAAbs/BrhoUtXTN7o/s160-c/Strip%252520Sunset.jpg",  

  86.             "https://lh5.googleusercontent.com/-at6apgFiN20/URqvDyffUZI/AAAAAAAAAbs/clABCx171bE/s160-c/Sunset%252520Hills.jpg",  

  87.             "https://lh4.googleusercontent.com/-7-EHhtQthII/URqvEYTk4vI/AAAAAAAAAbs/QSJZoB3YjVg/s160-c/Tenaya%252520Lake%2525202.jpg",  

  88.             "https://lh6.googleusercontent.com/-8MrjV_a-Pok/URqvFC5repI/AAAAAAAAAbs/9inKTg9fbCE/s160-c/Tenaya%252520Lake.jpg",  

  89.             "https://lh5.googleusercontent.com/-B1HW-z4zwao/URqvFWYRwUI/AAAAAAAAAbs/8Peli53Bs8I/s160-c/The%252520Cave%252520BW.jpg",  

  90.             "https://lh3.googleusercontent.com/-PO4E-xZKAnQ/URqvGRqjYkI/AAAAAAAAAbs/42nyADFsXag/s160-c/The%252520Fisherman.jpg",  

  91.             "https://lh4.googleusercontent.com/-iLyZlzfdy7s/URqvG0YScdI/AAAAAAAAAbs/1J9eDKmkXtk/s160-c/The%252520Night%252520is%252520Coming.jpg",  

  92.             "https://lh6.googleusercontent.com/-G-k7YkkUco0/URqvHhah6fI/AAAAAAAAAbs/_taQQG7t0vo/s160-c/The%252520Road.jpg",  

  93.             "https://lh6.googleusercontent.com/-h-ALJt7kSus/URqvIThqYfI/AAAAAAAAAbs/ejiv35olWS8/s160-c/Tokyo%252520Heights.jpg",  

  94.             "https://lh5.googleusercontent.com/-Hy9k-TbS7xg/URqvIjQMOxI/AAAAAAAAAbs/RSpmmOATSkg/s160-c/Tokyo%252520Highway.jpg",  

  95.             "https://lh6.googleusercontent.com/-83oOvMb4OZs/URqvJL0T7lI/AAAAAAAAAbs/c5TECZ6RONM/s160-c/Tokyo%252520Smog.jpg",  

  96.             "https://lh3.googleusercontent.com/-FB-jfgREEfI/URqvJI3EXAI/AAAAAAAAAbs/XfyweiRF4v8/s160-c/Tufa%252520at%252520Night.jpg",  

  97.             "https://lh4.googleusercontent.com/-vngKD5Z1U8w/URqvJUCEgPI/AAAAAAAAAbs/ulxCMVcU6EU/s160-c/Valley%252520Sunset.jpg",  

  98.             "https://lh6.googleusercontent.com/-DOz5I2E2oMQ/URqvKMND1kI/AAAAAAAAAbs/Iqf0IsInleo/s160-c/Windmill%252520Sunrise.jpg",  

  99.             "https://lh5.googleusercontent.com/-biyiyWcJ9MU/URqvKculiAI/AAAAAAAAAbs/jyPsCplJOpE/s160-c/Windmill.jpg",  

  100.             "https://lh4.googleusercontent.com/-PDT167_xRdA/URqvK36mLcI/AAAAAAAAAbs/oi2ik9QseMI/s160-c/Windmills.jpg",  

  101.             "https://lh5.googleusercontent.com/-kI_QdYx7VlU/URqvLXCB6gI/AAAAAAAAAbs/N31vlZ6u89o/s160-c/Yet%252520Another%252520Rockaway%252520Sunset.jpg",  

  102.             "https://lh4.googleusercontent.com/-e9NHZ5k5MSs/URqvMIBZjtI/AAAAAAAAAbs/1fV810rDNfQ/s160-c/Yosemite%252520Tree.jpg", };  

  103. }  

圖片源已經有了,如今咱們就該考慮在哪裏放置這些圖片了。新建或打開activity_main.xml做爲程序的主佈局,加入以下代碼:

[html] view plaincopy

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  2.     xmlns:tools="http://schemas.android.com/tools"  

  3.     android:layout_width="wrap_content"  

  4.     android:layout_height="wrap_content" >  

  5.       

  6.     <GridView   

  7.         android:id="@+id/photo_wall"  

  8.         android:layout_width="match_parent"  

  9.         android:layout_height="wrap_content"  

  10.         android:columnWidth="90dip"  

  11.         android:stretchMode="columnWidth"  

  12.         android:numColumns="auto_fit"  

  13.         android:verticalSpacing="10dip"  

  14.         android:gravity="center"  

  15.         ></GridView>  

  16.       

  17. </LinearLayout>  

能夠看到,咱們在這個佈局文件中僅加入了一個GridView,這也就是咱們程序中的「牆」,全部的圖片都將貼在這個「牆」上。

接着咱們定義GridView中每個子View的佈局,新建一個photo_layout.xml佈局,加入以下代碼:

[html] view plaincopy

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  2.     xmlns:tools="http://schemas.android.com/tools"  

  3.     android:layout_width="wrap_content"  

  4.     android:layout_height="wrap_content" >  

  5.   

  6.     <ImageView   

  7.         android:id="@+id/photo"  

  8.         android:layout_width="90dip"  

  9.         android:layout_height="90dip"  

  10.         android:src="@drawable/empty_photo"  

  11.         android:layout_centerInParent="true"  

  12.         />  

  13.   

  14. </RelativeLayout>  

在每個子View中咱們就簡單使用了一個ImageView來顯示一張圖片。這樣全部的佈局就已經定義好了。

接下來新建PhotoWallAdapter作爲GridView的適配器,代碼以下所示:

[java] view plaincopy

  1. public class PhotoWallAdapter extends ArrayAdapter<String> implements OnScrollListener {  

  2.   

  3.     /** 

  4.      * 記錄全部正在下載或等待下載的任務。 

  5.      */  

  6.     private Set<BitmapWorkerTask> taskCollection;  

  7.   

  8.     /** 

  9.      * 圖片緩存技術的核心類,用於緩存全部下載好的圖片,在程序內存達到設定值時會將最少最近使用的圖片移除掉。 

  10.      */  

  11.     private LruCache<String, Bitmap> mMemoryCache;  

  12.   

  13.     /** 

  14.      * GridView的實例 

  15.      */  

  16.     private GridView mPhotoWall;  

  17.   

  18.     /** 

  19.      * 第一張可見圖片的下標 

  20.      */  

  21.     private int mFirstVisibleItem;  

  22.   

  23.     /** 

  24.      * 一屏有多少張圖片可見 

  25.      */  

  26.     private int mVisibleItemCount;  

  27.   

  28.     /** 

  29.      * 記錄是否剛打開程序,用於解決進入程序不滾動屏幕,不會下載圖片的問題。 

  30.      */  

  31.     private boolean isFirstEnter = true;  

  32.   

  33.     public PhotoWallAdapter(Context context, int textViewResourceId, String[] objects,  

  34.             GridView photoWall) {  

  35.         super(context, textViewResourceId, objects);  

  36.         mPhotoWall = photoWall;  

  37.         taskCollection = new HashSet<BitmapWorkerTask>();  

  38.         // 獲取應用程序最大可用內存  

  39.         int maxMemory = (int) Runtime.getRuntime().maxMemory();  

  40.         int cacheSize = maxMemory / 8;  

  41.         // 設置圖片緩存大小爲程序最大可用內存的1/8  

  42.         mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {  

  43.             @Override  

  44.             protected int sizeOf(String key, Bitmap bitmap) {  

  45.                 return bitmap.getByteCount();  

  46.             }  

  47.         };  

  48.         mPhotoWall.setOnScrollListener(this);  

  49.     }  

  50.   

  51.     @Override  

  52.     public View getView(int position, View convertView, ViewGroup parent) {  

  53.         final String url = getItem(position);  

  54.         View view;  

  55.         if (convertView == null) {  

  56.             view = LayoutInflater.from(getContext()).inflate(R.layout.photo_layout, null);  

  57.         } else {  

  58.             view = convertView;  

  59.         }  

  60.         final ImageView photo = (ImageView) view.findViewById(R.id.photo);  

  61.         // 給ImageView設置一個Tag,保證異步加載圖片時不會亂序  

  62.         photo.setTag(url);  

  63.         setImageView(url, photo);  

  64.         return view;  

  65.     }  

  66.   

  67.     /** 

  68.      * 給ImageView設置圖片。首先從LruCache中取出圖片的緩存,設置到ImageView上。若是LruCache中沒有該圖片的緩存, 

  69.      * 就給ImageView設置一張默認圖片。 

  70.      *  

  71.      * @param imageUrl 

  72.      *            圖片的URL地址,用於做爲LruCache的鍵。 

  73.      * @param imageView 

  74.      *            用於顯示圖片的控件。 

  75.      */  

  76.     private void setImageView(String imageUrl, ImageView imageView) {  

  77.         Bitmap bitmap = getBitmapFromMemoryCache(imageUrl);  

  78.         if (bitmap != null) {  

  79.             imageView.setImageBitmap(bitmap);  

  80.         } else {  

  81.             imageView.setImageResource(R.drawable.empty_photo);  

  82.         }  

  83.     }  

  84.   

  85.     /** 

  86.      * 將一張圖片存儲到LruCache中。 

  87.      *  

  88.      * @param key 

  89.      *            LruCache的鍵,這裏傳入圖片的URL地址。 

  90.      * @param bitmap 

  91.      *            LruCache的鍵,這裏傳入從網絡上下載的Bitmap對象。 

  92.      */  

  93.     public void addBitmapToMemoryCache(String key, Bitmap bitmap) {  

  94.         if (getBitmapFromMemoryCache(key) == null) {  

  95.             mMemoryCache.put(key, bitmap);  

  96.         }  

  97.     }  

  98.   

  99.     /** 

  100.      * 從LruCache中獲取一張圖片,若是不存在就返回null。 

  101.      *  

  102.      * @param key 

  103.      *            LruCache的鍵,這裏傳入圖片的URL地址。 

  104.      * @return 對應傳入鍵的Bitmap對象,或者null。 

  105.      */  

  106.     public Bitmap getBitmapFromMemoryCache(String key) {  

  107.         return mMemoryCache.get(key);  

  108.     }  

  109.   

  110.     @Override  

  111.     public void onScrollStateChanged(AbsListView view, int scrollState) {  

  112.         // 僅當GridView靜止時纔去下載圖片,GridView滑動時取消全部正在下載的任務  

  113.         if (scrollState == SCROLL_STATE_IDLE) {  

  114.             loadBitmaps(mFirstVisibleItem, mVisibleItemCount);  

  115.         } else {  

  116.             cancelAllTasks();  

  117.         }  

  118.     }  

  119.   

  120.     @Override  

  121.     public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,  

  122.             int totalItemCount) {  

  123.         mFirstVisibleItem = firstVisibleItem;  

  124.         mVisibleItemCount = visibleItemCount;  

  125.         // 下載的任務應該由onScrollStateChanged裏調用,但首次進入程序時onScrollStateChanged並不會調用,  

  126.         // 所以在這裏爲首次進入程序開啓下載任務。  

  127.         if (isFirstEnter && visibleItemCount > 0) {  

  128.             loadBitmaps(firstVisibleItem, visibleItemCount);  

  129.             isFirstEnter = false;  

  130.         }  

  131.     }  

  132.   

  133.     /** 

  134.      * 加載Bitmap對象。此方法會在LruCache中檢查全部屏幕中可見的ImageView的Bitmap對象, 

  135.      * 若是發現任何一個ImageView的Bitmap對象不在緩存中,就會開啓異步線程去下載圖片。 

  136.      *  

  137.      * @param firstVisibleItem 

  138.      *            第一個可見的ImageView的下標 

  139.      * @param visibleItemCount 

  140.      *            屏幕中總共可見的元素數 

  141.      */  

  142.     private void loadBitmaps(int firstVisibleItem, int visibleItemCount) {  

  143.         try {  

  144.             for (int i = firstVisibleItem; i < firstVisibleItem + visibleItemCount; i++) {  

  145.                 String imageUrl = Images.imageThumbUrls[i];  

  146.                 Bitmap bitmap = getBitmapFromMemoryCache(imageUrl);  

  147.                 if (bitmap == null) {  

  148.                     BitmapWorkerTask task = new BitmapWorkerTask();  

  149.                     taskCollection.add(task);  

  150.                     task.execute(imageUrl);  

  151.                 } else {  

  152.                     ImageView imageView = (ImageView) mPhotoWall.findViewWithTag(imageUrl);  

  153.                     if (imageView != null && bitmap != null) {  

  154.                         imageView.setImageBitmap(bitmap);  

  155.                     }  

  156.                 }  

  157.             }  

  158.         } catch (Exception e) {  

  159.             e.printStackTrace();  

  160.         }  

  161.     }  

  162.   

  163.     /** 

  164.      * 取消全部正在下載或等待下載的任務。 

  165.      */  

  166.     public void cancelAllTasks() {  

  167.         if (taskCollection != null) {  

  168.             for (BitmapWorkerTask task : taskCollection) {  

  169.                 task.cancel(false);  

  170.             }  

  171.         }  

  172.     }  

  173.   

  174.     /** 

  175.      * 異步下載圖片的任務。 

  176.      *  

  177.      * @author guolin 

  178.      */  

  179.     class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {  

  180.   

  181.         /** 

  182.          * 圖片的URL地址 

  183.          */  

  184.         private String imageUrl;  

  185.   

  186.         @Override  

  187.         protected Bitmap doInBackground(String... params) {  

  188.             imageUrl = params[0];  

  189.             // 在後臺開始下載圖片  

  190.             Bitmap bitmap = downloadBitmap(params[0]);  

  191.             if (bitmap != null) {  

  192.                 // 圖片下載完成後緩存到LrcCache中  

  193.                 addBitmapToMemoryCache(params[0], bitmap);  

  194.             }  

  195.             return bitmap;  

  196.         }  

  197.   

  198.         @Override  

  199.         protected void onPostExecute(Bitmap bitmap) {  

  200.             super.onPostExecute(bitmap);  

  201.             // 根據Tag找到相應的ImageView控件,將下載好的圖片顯示出來。  

  202.             ImageView imageView = (ImageView) mPhotoWall.findViewWithTag(imageUrl);  

  203.             if (imageView != null && bitmap != null) {  

  204.                 imageView.setImageBitmap(bitmap);  

  205.             }  

  206.             taskCollection.remove(this);  

  207.         }  

  208.   

  209.         /** 

  210.          * 創建HTTP請求,並獲取Bitmap對象。 

  211.          *  

  212.          * @param imageUrl 

  213.          *            圖片的URL地址 

  214.          * @return 解析後的Bitmap對象 

  215.          */  

  216.         private Bitmap downloadBitmap(String imageUrl) {  

  217.             Bitmap bitmap = null;  

  218.             HttpURLConnection con = null;  

  219.             try {  

  220.                 URL url = new URL(imageUrl);  

  221.                 con = (HttpURLConnection) url.openConnection();  

  222.                 con.setConnectTimeout(5 * 1000);  

  223.                 con.setReadTimeout(10 * 1000);  

  224.                 con.setDoInput(true);  

  225.                 con.setDoOutput(true);  

  226.                 bitmap = BitmapFactory.decodeStream(con.getInputStream());  

  227.             } catch (Exception e) {  

  228.                 e.printStackTrace();  

  229.             } finally {  

  230.                 if (con != null) {  

  231.                     con.disconnect();  

  232.                 }  

  233.             }  

  234.             return bitmap;  

  235.         }  

  236.   

  237.     }  

  238.   

  239. }  

PhotoWallAdapter是整個照片牆程序中最關鍵的一個類了,這裏我來重點給你們講解一下。首先在PhotoWallAdapter的構造函數中,咱們初始化了LruCache類,並設置了最大緩存容量爲程序最大可用內存的1/8,接下來又爲GridView註冊了一個滾動監聽器。而後在getView()方法中,咱們爲每一個ImageView設置了一個惟一的Tag,這個Tag的做用是爲了後面可以準確地找回這個ImageView,否則異步加載圖片會出現亂序的狀況。以後調用了setImageView()方法爲ImageView設置一張圖片,這個方法首先會從LruCache緩存中查找是否已經緩存了這張圖片,若是成功找到則將緩存中的圖片顯示在ImageView上,不然就顯示一張默認的空圖片。

看了半天,那究竟是在哪裏下載圖片的呢?這是在GridView的滾動監聽器中進行的,在onScrollStateChanged()方法中,咱們對GridView的滾動狀態進行了判斷,若是當前GridView是靜止的,則調用loadBitmaps()方法去下載圖片,若是GridView正在滾動,則取消掉全部下載任務,這樣能夠保證GridView滾動的流暢性。在loadBitmaps()方法中,咱們爲屏幕上全部可見的GridView子元素開啓了一個線程去執行下載任務,下載成功後將圖片存儲到LruCache當中,而後經過Tag找到相應的ImageView控件,把下載好的圖片顯示出來。

因爲咱們使用了LruCache來緩存圖片,因此不須要擔憂內存溢出的狀況,當LruCache中存儲圖片的總大小達到容量上限的時候,會自動把最近最少使用的圖片從緩存中移除。

最後新建或打開MainActivity做爲程序的主Activity,代碼以下所示:

[java] view plaincopy

  1. public class MainActivity extends Activity {  

  2.   

  3.     /** 

  4.      * 用於展現照片牆的GridView 

  5.      */  

  6.     private GridView mPhotoWall;  

  7.   

  8.     /** 

  9.      * GridView的適配器 

  10.      */  

  11.     private PhotoWallAdapter adapter;  

  12.   

  13.     @Override  

  14.     protected void onCreate(Bundle savedInstanceState) {  

  15.         super.onCreate(savedInstanceState);  

  16.         setContentView(R.layout.activity_main);  

  17.         mPhotoWall = (GridView) findViewById(R.id.photo_wall);  

  18.         adapter = new PhotoWallAdapter(this0, Images.imageThumbUrls, mPhotoWall);  

  19.         mPhotoWall.setAdapter(adapter);  

  20.     }  

  21.   

  22.     @Override  

  23.     protected void onDestroy() {  

  24.         super.onDestroy();  

  25.         // 退出程序時結束全部的下載任務  

  26.         adapter.cancelAllTasks();  

  27.     }  

  28.   

  29. }  

MainActivity中的代碼很是簡單,沒什麼須要說明的了,在Activity被銷燬時取消掉了全部的下載任務,避免程序在後臺耗費流量。另外因爲咱們使用了網絡功能,別忘了在AndroidManifest.xml中加入網絡權限的聲明。

如今能夠運行一下程序了,效果以下圖所示:

                                          

能夠看到,滾動照片牆,會異步加載圖片到相應的ImageView上。隨着加載圖片的增多,會釋放掉一些以前加載過的圖片,你多滾動幾回就能夠看得出了。另外爲了能讓你們明顯看出圖片的釋放狀況,我在這個程序中沒有使用本地緩存,全部被釋放掉的圖片再次顯示須要從網絡上再下載一遍。在實際的項目中配合適當的本地緩存效果會更好。

打開DDMS,咱們能夠發現,因爲有LruCache幫咱們管理圖片緩存,無論如何滾動照片牆,程序內存始終會保持在一個合理的範圍內。


本篇文章的重點在於如何對圖片進行更好的回收,所以照片牆只是簡單地使用GridView進行了展現,想要看更酷更炫的照片牆效果的朋友,能夠參考我後面的一篇文章 Android瀑布流照片牆實現,體驗不規則排列的美感 。

好了,今天的講解到此結束,有疑問的朋友請在下面留言。

源碼下載,請點擊這裏

相關文章
相關標籤/搜索