Android gallery asynchronously loads network images

Source: Internet
Author: User

I have found a lot of materials on the Internet, but the approximate effect is that the image is not downloaded when the gallery slides, and the current page image is loaded when the gallery slide stops, I spent a little time doing this. If you have better suggestions, let us know how to study together.
First look at the effect:
This figure is the default image displayed when the image is loaded. It is replaced when the image is loaded.

Image loaded

  1. Import Java. util. arraylist; import Java. util. hashmap; import Java. util. list; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapfactory; import android. OS. asynctask; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. keyevent; import android. view. view; import android. widget. adapterview; import androi D. widget. adapterview. onitemclicklistener; import android. widget. adapterview. onitemselectedlistener; import android. widget. gallery; public class myactivity extends activity implements onitemclicklistener {public static hashmap <string, bitmap> imagescache = new hashmap <string, bitmap> (); // private gallery images_ga; public static imageadapter; private int num = 0; List <string> URLs = new Rraylist <string> (); // list of all image addresses <string> url = new arraylist <string> (); // URL of the image to be downloaded @ override protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. gallery_1); files. mkdir (this); Init ();} private void Init () {bitmap image = bitmapfactory. decoderesource (getresources (), R. drawable. default_movie_post); imagescache. put ("background_non_l Oad ", image); // set the default image images_ga = (Gallery) findviewbyid (R. id. gallery); URLs. add ("http://hiphotos.baidu.com/baidu/pic/item/f603918fa0ec08fabf7a641659ee3d6d55fbda0d.jpg"); URLs. add ("http://hiphotos.baidu.com/baidu/pic/item/43a7d933c895d143d011bf9273f082025aaf071f.jpg"); URLs. add ("http://hiphotos.baidu.com/baidu/pic/item/63d0f703918fa0ec2ebf584b269759ee3d6ddb7f.jpg"); URLs. add ("http://hiphotos. B Parameters "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/item/8601a18b87d6277f6e46217628381f30e924fc2c.jpg "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/item/b48f8c54acf9964c3a29350e.jpg "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/item/bd3eb13533fa828b48da6aabfd1f4134960a5af9.jpg "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/ I "); TEM/29381f30e924b899da3ce5706e061d950a7bf672.jpg "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/item/bd3eb13533fa828b48da6aabfd1f4134960a5af9.jpg "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/item/4bed2e738bd4b31cd73d63fd87d6277f9e2ff877.jpg "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/item/caef76094b36acaf92b619b87cd98d1001e99c24.jpg "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/item/ 8435e5dde71190efd6154d95ce1b9d16fcfa608a.jpg "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/item/b3de9c824ba1d4cd6d81190f.jpg "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/item/e0fe9925cc2c683834a80f11.jpg "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/item/0bd162d9f2d3572c65911a988a13632762d0c307.jpg "); URLs. Add (" http://hiphotos.baidu.com/baidu/pic/item/ac6eddc451da81cb2ac1708a5266d0160924 3155. jpg "); URLs. add ("http://hiphotos.baidu.com/baidu/pic/item/1bd5ad6e8416d98080cb4a48.jpg"); URLs. add ("http://hiphotos.baidu.com/baidu/pic/item/3c6d55fbb2fb43169d0508ca20a4462309f7d36c.jpg"); URLs. add ("http://hiphotos.baidu.com/baidu/pic/item/faedab64034f78f0daf3664a79310a55b2191c8a.jpg"); URLs. add ("http://hiphotos.baidu.com/baidu/pic/item/2fdda3cc7cd98d10b05af088213fb80e7aec90f9.jpg"); URLs. add ("Http://hiphotos.baidu.com/baidu/pic/item/b8014a90f603738d9536f39bb31bb051f819ec0f.jpg"); URLs. add ("http://hiphotos.baidu.com/baidu/pic/item/2fdda3cc7cd98d10b05af088213fb80e7aec90f9.jpg"); imageadapter = new imageadapter (URLs, this); images_ga.setadapter (imageadapter); images_ga.setonitemclicklistener (this); listener (New onitemselectedlistener () {@ override public void Onitemselected (adapterview <?> Arg0, view arg1, int arg2, long arg3) {num = arg2; log. I ("Mahua", "itemselected =" + arg2); gallerywhetherstop () ;}@ override public void onnothingselected (adapterview <?> Arg0) {// todo auto-generated method stub}) ;}@ overridepublic void onitemclick (adapterview <?> Arg0, view arg1, int arg2, long arg3) {log. I ("golf", "Number" + arg2 + "clicked");}/*** determines whether the gallery rolling is stopped, if it is stopped, the image of the current page will be loaded */private void gallerywhetherstop () {runnable = new runnable () {public void run () {try {int Index = 0; index = num; thread. sleep (1000); If (Index = num) {URL. add (URLs. get (Num); If (num! = 0 & URLs. Get (num-1 )! = NULL) {URL. Add (URLs. Get (num-1);} If (num! = URLs. Size ()-1 & URLs. Get (Num + 1 )! = NULL) {URL. add (URLs. get (Num + 1);} message m = new message (); M. what = 1; mhandler. sendmessage (m) ;}} catch (exception e) {e. printstacktrace () ;}}; new thread (runnable ). start () ;}// asynchronous task class loadimagetask extends asynctask <string, void, bitmap >{@ override protected void oncancelled () {// todo auto-generated method stub super. oncancelled () ;}@ override protected void onpostexecute (Bi TMAP result) {// todo auto-generated method stub super. onpostexecute (result) ;}@ override protected bitmap doinbackground (string... params) {Bitmap bitmap = NULL; try {string url = Params [0]; Boolean isexists = files. compare (URL); // This is a self-written tool class, used to determine whether the local cache has downloaded the image if (isexists = false) {// download the image. Net = new net (); byte [] DATA = net. downloadresource (myactivity. this, URL); bitmap = bitmapfacto Ry. decodebytearray (data, 0, Data. length); imagescache. put (URL, bitmap); // Save the downloaded image to the cache files. saveimage (URL, data);} else {// if any, read the cached image byte [] DATA = files. readImage (URL); bitmap = bitmapfactory. decodebytearray (data, 0, Data. length); imagescache. put (URL, bitmap); // Save the downloaded image to the cache} message m = new message (); // reload m after the image is loaded. what = 0; mhandler. sendmessage (m);} catch (exception e) {e. printst Acktrace ();} return bitmap;} private handler mhandler = new handler () {public void handlemessage (Message MSG) {try {Switch (MSG. what) {Case 0: {imageadapter. notifydatasetchanged (); break;} Case 1: {for (INT I = 0; I <URL. size (); I ++) {loadimagetask task = new loadimagetask (); // asynchronously load the image task.exe cute (URL. get (I); log. I ("Mahua", URL. get (I);} URL. clear () ;}} super. handlemessage (MSG);} catch (Exception e) {e. printstacktrace () ;}};@ overridepublic Boolean onkeydown (INT keycode, keyevent event) {If (keycode = keyevent. keycode_back) {system. exit (0);} return Super. onkeydown (keycode, event) ;}import Java. util. list; import android. content. context; import android. content. res. assetmanager; import android. content. res. typedarray; import android. graphics. bitmap; import android. view. view; import android Oid. view. viewgroup; import android. widget. baseadapter; import android. widget. gallery; import android. widget. imageview; public class imageadapter extends baseadapter {public static final baseadapter adapter = NULL; private list <string> imageurls; // The image address listprivate context; int mgalleryitembackground; public imageadapter (list <string> imageurls, context) {This. imageurls = imageurls; this. con TEXT = context; // * used in res/values/attrs. the gallery attribute defined by <declare-styleable> in XML. // */typedarray A = context. obtainstyledattributes (R. styleable. gallery1);/* obtain the index ID of the gallery attribute */mgalleryitembackground =. getresourceid (R. styleable. gallery1_android_galleryitembackground, 0);/* enables the object's styleable attribute to be used repeatedly */. recycle ();} public int getcount () {return imageurls. size ();} public object getitem (INT position) {Return imageurls. get (position);} public long getitemid (INT position) {return position;} public view getview (INT position, view convertview, viewgroup parent) {bitmap image; imageview view = new imageview (context); image = myactivity. imagescache. get (imageurls. get (position); // read the image from the cache if (image = NULL) {image = myactivity. imagescache. get ("background_non_load");} // set the resource address view for all images. setimagebitmap (IMA Ge); view. setscaletype (imageview. scaletype. fit_xy); view. setlayoutparams (new gallery. layoutparams (240,320); view. setbackgroundresource (mgalleryitembackground);/* set the gallery background image */return view;} attrs. XML <? XML version = "1.0" encoding = "UTF-8"?> <Resources> <declare-styleable name = "toggleprefattrs"> <ATTR name = "Android: preferencelayoutchild"/> </declare-styleable> <! -- These are the attributes that we want to retrieve from the themein view/gallery1.java --> <declare-styleable name = "gallery1"> <ATTR name = "Android: galleryitembackground "/> </declare-styleable> <declare-styleable name =" labelview "> <ATTR name =" text "format =" string "/> <ATTR name =" textcolor "format =" color "/> <ATTR name =" textsize "format =" dimension "/> </declare-styleable> </resources>


The main structure is like this. Just download the file and save it and write it as needed. If you have better suggestions, please share them with us.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.