First of all, how to download text and pictures in the ListView, you can look at my previous Bloglistview get network data display.
So here about how to download XML data for the first time, binding adapter, etc. is not more detailed, mainly to share how to use Imageloader in the ListView this open source framework to download the image below.
First introduce the Imageloader. Users in the rapid drag when the phenomenon is prone to lag, may not be downloaded in time, and then sometimes may appear the wrong item ImageView and other issues, the use of open source framework Imageloader can better control the problem.
First of all, the use of imageloader need to pay attention to the place, we can go to see a piece of blog:http://blog.csdn.net/liweijie_chengxuyuan/article/details/45222167
First, let's go ahead and configure application
His code is as follows: You need to set him in the manifest file, as the value of the Name property of the application, note that if the class is no longer under the project package, the settings need to add his full package path + class name
Import Java.io.file;import Android.app.application;import Android.content.context;import Com.nostra13.universalimageloader.cache.disc.impl.unlimiteddisccache;import Com.nostra13.universalimageloader.cache.disc.naming.md5filenamegenerator;import Com.nostra13.universalimageloader.core.imageloader;import Com.nostra13.universalimageloader.core.imageloaderconfiguration;import Com.nostra13.universalimageloader.core.assist.queueprocessingtype;import Com.nostra13.universalimageloader.utils.storageutils;public class MyApplication extends application{@ overridepublic void OnCreate () {super.oncreate (); Initimageloader (Getapplicationcontext ());} public static void Initimageloader (context context) {File cache = storageutils.getowncachedirectory (context, "liweijie/ Cache "), imageloaderconfiguration config = new Imageloaderconfiguration.builder (context). ThreadPriority (Thread.norm _PRIORITY-2)//Set the priority of the Imageloader thread. ThreadPoolSize (3)//Set the maximum number of his thread pools recommended 1-5, prevent oom, do not set it too large. Disccache (new Unlimiteddisccache (Cache)//Set the file cache to the SD card or the location of the phone. Denycacheimagemultiplesizesinmemory ()//Set. Disccachefilenamegenerator (New Md5filenamegenerator ())///Image encoding Method MD5 encoded. Tasksprocessingorder (QUEUEPROCESSINGTYPE.LIFO)//default. Writedebuglogs (). Build (); Imageloader.getinstance (). init (config); Initialize the configuration of the Imageloader, must}}Imageloader uses a singleton design pattern, imageloader Imageloader = Imageloader.getinstance (), and gets the object, each Imageloader using a singleton design pattern, Imageloader must call the init () method to complete the initialization.
When using these two points are to be noted, one is intiimageloader in the application, in the manifest file to add access to network permissions.
Then for the various settings of the picture can be set through the displayimageoptions, according to their own needs to set up good.
Isplayimageoptions options; options = new Displayimageoptions.builder (). showimageonloading (R.drawable.ic_launcher)//Set the picture to be displayed during the download. Showimag Eforemptyuri (R.drawable.ic_launcher)//Set the picture URI to be empty or wrong when the picture is displayed. Showimageonfail (r.drawable.ic_launcher)//Set Picture loading/ The image that is displayed when the error is decoded. Cacheinmemory (TRUE)//sets whether the downloaded picture is in memory. Cacheondisc (TRUE)//sets whether the downloaded picture is slow to exist on the SD card. Considerexifparams ( true)//whether to consider the JPEG image exif parameter (rotate, flip). Imagescaletype (imagescaletype.exactly_stretched)//Set the image to display in how it is encoded. Bitmapconfig ( Bitmap.Config.RGB_565)//Set the decoding type of the picture//. Decodingoptions (android.graphics.BitmapFactory.Options decodingoptions)// Set the decoding configuration of the picture//.delaybeforeloading (int delayinmillis)//int Delayinmillis for you to set the delay time before the download//set the picture before adding the cache, set bitmap//.prepr Ocessor (Bitmapprocessor Preprocessor). Resetviewbeforeloading (TRUE)//Set whether the picture is reset before downloading, reset. Displayer (New Roundedbitmapdisplayer (20))//whether set to rounded corners, how many radians. Displayer (new Fadeinbitmapdisplayer (100))//Whether the picture is loaded and the animation time is gradually entered. build (); /Build Complete
The Imageloader method to use when downloading images in adapter isdisplayimage () and LoadImage () are the two methods. This blog uses displayimage () method, he is relatively easy to use.
Download is the details of this demo:
Approximate Project framework:
Mainactivity code: His role is to initialize the image configuration, as above the displayimageoptions , he is inheriting from baseactivity (below), and then he is going to open a thread to download XML data on the server , containing the displayed text and the URL of the picture, by using the handler mechanism to bind the adapter, the load data is fully bound adapter, the adapter runs on the UI thread, it contains a Imageloader object responsible for downloading the corresponding image display.
Import Java.io.ioexception;import java.util.arraylist;import Java.util.list;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.view.window;import Android.widget.ListView;import Android.widget.toast;import Com.example.myimageloader.domain.news;import Com.nostra13.universalimageloader.core.displayimageoptions;import Com.nostra13.universalimageloader.core.display.roundedbitmapdisplayer;public class MainActivity extends Baseactivity{private displayimageoptions options;private ListView listview;private list<news> datas = new Arraylist<news> ();p rivate Handler mhandler = new Handler () {public void Handlemessage (Android.os.Message msg) {if ( Msg.what = = 1) {System.out.println (((list<news>) msg.obj). Size ()); Listview.setadapter (New Mylistadapter (List <News>) Msg.obj, Mainactivity.this, Imageloader, options);} else if (msg.what = =-1) {Toast.maketext (Getapplicationcontext (), "Network problematic", Toast.length_short). Show ();};}; @Overrideprotected VoiD onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_ TITLE); Setcontentview (r.layout.activity_main); listview = (ListView) This.findviewbyid (r.id.mylistview); options = New Displayimageoptions.builder (). Showstubimage (R.drawable.ic_launcher)//settings picture is not downloaded completely before the picture is displayed. Showimageforemptyuri (r.drawable.ic_empty)//Set the image to be displayed when the URL is empty or when it is wrong. Showimageonfail (r.drawable.ic_error)// Sets the picture to load or to be displayed during a decoding error. Cacheinmemory (TRUE)//settings can be slowed in memory. Cacheondisc (TRUE)//settings can be slow to exist on the SD card or on the phone. Displayer (New Roundedbitmapdisplayer (20))//set to rounded picture. Build ();//Create a Displayimageoption object that is configured with new Mythredloadnews (Datas, Mhandler). Start ();}} Final class Mythredloadnews extends Thread{private list<news> datas;private Handler handler;public Mythredloadnews (list<news> datas, Handler Handler) {This.datas = Datas;this.handler = Handler;} @Overridepublic void Run () {Try{datas.addall (Newsservice.getdata ()); System.out.println (Newsservice.getdata (). Size ()); Message msg = MessagE.obtain (); msg.what = 1;msg.obj = Datas;handler.sendmessage (msg);} catch (IOException e) {handler.sendemptymessage ( -1); E.printstacktrace ();} catch (Exception e) { Handler.sendemptymessage ( -1); E.printstacktrace ();}}}Baseactivity's role is to deal with the menu, if some of the phone does not have a menu button when he clicks Actionbar will pop out, there is a menu button will automatically eject, there are two menus, one is to clear the memory cache, one is to clear the local cache phone. And in charge of instantiating Imageloader is inherited by Mainactivity, he has no interface and does not want to declare in the manifest file.
public class Baseactivity extends activity{protected imageloader imageloader = Imageloader.getinstance (); Overridepublic boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {case R.id.item_clear_memory_ Cache:imageLoader.clearMemoryCache (); return true;case R.id.item_clear_disc_cache:imageloader.cleardiskcache (); return True;default:return false;}}}
Service class, which is responsible for downloading and parsing XML data in a
Import Java.io.ioexception;import java.io.inputstream;import Java.net.httpurlconnection;import Java.net.URL;import Java.util.arraylist;import Java.util.list;import Org.xmlpull.v1.xmlpullparser;import Android.util.Xml;import Com.example.myimageloader.domain.news;public class newsservice{//download XML data public static list<news> GetData () Throws Exception, ioexception{string path = "Http://192.168.1.109:8080/web/mylist1.xml"; HttpURLConnection conn = (httpurlconnection) new URL (path). OpenConnection (); conn.setconnecttimeout (5000); Conn.setconnecttimeout (Conn.setrequestmethod); ("GET"), if (+ = = Conn.getresponsecode ()) {InputStream stream = Conn.getinputstream (); return Parserxml (stream);} return null;} <span style= "White-space:pre" ></span>//parsing XML data private static list<news> Parserxml (InputStream Stream) throws exception{list<news> datas = new arraylist<news> (); News news = null; Xmlpullparser parser = Xml.newpullparser ();p arser.setinput (Stream, "UTF-8"); int event = Parser.geteventtype (); while (event! = xmlpullparser.end_document) {switch (event) {case Xmlpullparser.start_tag : if ("image". Equals (Parser.getname ())) {news = new News (); news.name = Parser.getattributevalue (0); break;} if ("Path". Equals (Parser.getname ())) {News.path = Parser.nexttext (); break;} Break;case XmlPullParser.END_TAG:if ("image". Equals (Parser.getname ())) {Datas.add (news); news = Null;break;} break;} event = Parser.next ();} return datas;}}Adapter class, his role is to contact the data and the ListView, and then enable Imageloader to download the picture of the corresponding item
Import Java.util.arraylist;import java.util.collections;import Java.util.linkedlist;import Java.util.List;import Android.content.context;import Android.graphics.bitmap;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.ImageView ; Import Android.widget.textview;import Com.example.myimageloader.domain.news;import Com.nostra13.universalimageloader.core.displayimageoptions;import Com.nostra13.universalimageloader.core.imageloader;import Com.nostra13.universalimageloader.core.display.fadeinbitmapdisplayer;import Com.nostra13.universalimageloader.core.listener.imageloadinglistener;import Com.nostra13.universalimageloader.core.listener.simpleimageloadinglistener;public class MyListAdapter extends Baseadapter{private Imageloadinglistener listener = new Firstdisplatlistener ();p rivate list<news> datas = new Arraylist<news> ();p rivate layoutinflater inflater;private imageloader imageloader;priVate displayimageoptions options;public mylistadapter (list<news> datas, Context context,imageloader ImageLoader , displayimageoptions options) {this.datas.addAll (datas); inflater = (layoutinflater) context.getsystemservice ( Context.layout_inflater_service); this.imageloader = imageloader;this.options = options; System.out.println ("ok111"); System.out.println (This.datas.size ());} @Overridepublic int GetCount () {return datas.size ();} @Overridepublic Object getItem (int position) {return datas.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Viewholder holder = null;if (Null = = Conver TView) {holder = new Viewholder (); Convertview = Inflater.inflate (R.layout.list_item, null); Holder.imageview = ( ImageView) Convertview.findviewbyid (r.id.image); Holder.textview = (TextView) Convertview.findviewbyid (R.id.text); Convertview.settag (holder);} Else{holder = (Viewholder) Convertview.gettag ();} System.out. println ("Okliweijie"); News news = Datas.get (position), Holder.textView.setText (News.name + "+item" + (position + 1)); Imageloader.displayimage ( News.path, Holder.imageview, options, listener); return convertview;} Private class Viewholder{public TextView textview;public ImageView ImageView;} private static class Firstdisplatlistener extends Simpleimageloadinglistener{static final list<string> Diaplayimages = collections.synchronizedlist (New linkedlist<string> ()); @Overridepublic void Onloadingcomplete (String Imageuri, view view, Bitmap loadedimage) {if (loadedimage = = null) {ImageView ImageView = (ImageView) View;boolean firstdisplay =!diaplayimages.contains (Imageuri if (firstdisplay)//does not exist, this is the first display, using a gradient animation, and then the URI corresponding to the imageview stored in the list {fadeinbitmapdisplayer.animate ( ImageView,;d Iaplayimages.add (Imageuri);}}}}Application class, Configuration Imageloader, first on top. Where news is a class that contains the name and path two attributes, no code is posted. Results
Use Imageloader framework to download network picture display in ListView