Android Universal-image-loader Framework Learning

Source: Internet
Author: User

I. Universal-image-loader Overview:

Android-universal-image-loader is an open-source picture loading framework, the purpose of this project is to provide a reusable instrument for asynchronous image loading, caching and display.

Features of the Open Source Library:

(1). Multi-threaded download picture.

(2). Configurable by configuring Imageloader, changing the thread pool, picture downloader, and so on.

(3). Supports images in memory cache, file system cache or SD card cache.

(4). Support for image download monitoring.

(5). It is better to control the loading process of the picture, such as stop loading the picture when the ListView is sliding, and load the picture when the slide stops.

Some other features go to http://blog.csdn.net/xiaanming/article/details/26810303 the great God blog to see it.


Two. Simple to use:

When it is not loaded:


Load succeeded:


After importing the jar package in the project, we need to configure the imageloaderconfiguration, this is the global picture cache also thread, cache size, parsing and so on to configure, and then Imageloader is the implementation of the specific implementation of downloading pictures, cache pictures display pictures, The configured imageloaderconfiguration is passed into the Imageloader to complete the initialization work, that is, after initialization to use the imageloader. GetInstance (). DisplayImage () loads the picture.

The initialization of the Imageloader can be implemented in application:

public class MyApp extends application {@Overridepublic void OnCreate () {super.oncreate (); InitImageLoader1 ( Getapplicationcontext ());} /* Custom configuration */public static void Initimageloader (context context) {Imageloaderconfiguration.builder config = new Imageloade Rconfiguration.builder (context); config.threadpoolsize (3);//Line Cheng Chinega the number of config.threadpriority (thread.norm_priority -2); Config.denycacheimagemultiplesizesinmemory ()//Do not cache multiple dimensions of a picture in memory Config.diskcachefilenamegenerator (new Md5filenamegenerator ());//will save the URI name with Md5config.diskcachesize (50 * 1024 * 1024); Mibconfig.tasksprocessingorder (QUEUEPROCESSINGTYPE.LIFO); Config.writedebuglogs ();//Remove for release app// Initialize Imageloaderimageloader.getinstance (). Init (Config.build ());} /* * Default configuration, generally no special requirements when the use of the default is good. */public static void InitImageLoader1 (context context) {//create default imageloader configuration Parameters imageloaderconfiguration Config = Imageloaderconfiguration.createdefault (context);//Initialize Imageloaderimageloader.getinstance (). Init (configuration) ;}}

In Diskcachefilenamegenerator (); This is how the cached file is named in the following two ways:

1.new md5filenamegenerator ()//use MD5 to encrypt UIL name

2.new Hashcodefilenamegenerator ()//use Hashcode to encrypt UIL name




Then under the Androidmanifest.xml configuration:

<!--network permissions and Cache permissions--<span style= "color: #ff0000;" ><uses-permission android:name= "Android.permission.INTERNET"/> <uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/></span> <application android:name=" Com.example.androidi Mageview. MyApp "android:allowbackup=" true "android:icon=" @drawable/ic_launcher "android:label=" @string/app_nam E "android:theme=" @style/apptheme "> <activity <span style=" color: #ff0000; "             >android:name= "com.example.androidimageview.MainActivity" </span> android:label= "@string/app_name" >                <intent-filter> <action android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity > </application>
To define a layout file:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "     >   <listview android:id= "@+id/listview1" android:layout_width= "Fill_parent" android:layout_height= " Fill_parent "/></relativelayout>

Picture PlusDownloadwith displayimageoptions, we can configure this image to display the options, before the tablet load is completed before the display of what pictures, loading failed to show what pictures and so on:

<span style= "FONT-SIZE:24PX;" >options = new Displayimageoptions.builder (). showimageonloading (r.drawable.ic_stub)//Set the picture to be displayed during download. Showimageforemptyuri (R.drawable.ic_empty)//Set the picture URI to be empty or wrong when the picture is displayed. Showimageonfail (r.drawable.ic_error)//Set Picture loading/ The image that is displayed when the error is in the decoding process. delaybeforeloading (1000)//Set the time delay after which the download begins. Cacheinmemory (TRUE)//sets whether the downloaded picture is in memory. Cacheondisk (TRUE)/ /Set whether the downloaded resource is slow to exist on the SD card. Considerexifparams (TRUE)//whether the JPEG image is considered as an EXIF parameter (rotate, flip). Imagescaletype (Imagescaletype.in_sample_ power_of_2)//Set How the picture is displayed in the encoding. Bitmapconfig (Bitmap.Config.RGB_565)//Set the decoding type of the picture. Displayer (New Roundedbitmapdisplayer ( 20)//Whether it is set to rounded corners, how many radians. Displayer (New Fadeinbitmapdisplayer (1000))//Whether the picture is loaded and the animation time is gradually entered. Build ();</span>

The display size of the picture will be based on the arrogance of your imageview in the configuration above:

Imagescaletype (Imagescaletype imagescaletype):

Scale type Magescaletype:

(1). Exactly: the target size at which the image will be scaled down completely.

(2). Exactly_stretched: The picture zooms to the target size completely

(3). In_sample_int: The image will be sampled in multiples of two times

(4). In_sample_power_of_2: The picture will be lowered twice times until the next reduction step to make the image smaller target size

(5). NONE: Picture does not adjust

The layout of the item:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" wrap_content "><imageviewandroid:id=" @+ Id/image "android:layout_width=" 72DP "android:layout_height=" 72DP "android:layout_margin=" 3dip "Android: Adjustviewbounds= "true" android:contentdescription= "@string/descr_image" android:scaletype= "Centercrop"/>< Textviewandroid:id= "@+id/text" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android: Layout_gravity= "start|center_vertical" android:layout_marginleft= "20dip" android:textsize= "22SP"/></ Linearlayout>


main interface implementation:

public class Mainactivity extends Activity {private static final String Test_file_name = "Universal Image Loader @#&=+ -_.,! () ~ '%20.png '; ListView listview1;p ublic static final string[] IMAGES = new string[] {"http://img.dapixie.com/uploads/allimg/111105/    1-111105145231.jpg "};        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        ListView1 = (ListView) Findviewbyid (R.ID.LISTVIEW1);    Listview1.setadapter (New Imageadapter (this));    } @Override protected void OnDestroy () {Super.ondestroy ();    AnimateFirstDisplayListener.displayedImages.clear ();    Imageloader.getinstance (). Clearmemorycache ();    Imageloader.getinstance (). Stop (); } private static Class Imageadapter extends Baseadapter {private static final string[] Image_urls = mainactivity.im Ages;private layoutinflater inflater;private Imageloadinglistener animatefirstlistener = new AnimateFirstDIsplaylistener ();p rivate displayimageoptions options;imageadapter (context context) {Inflater = Layoutinflater.from ( context); options = new Displayimageoptions.builder (). showimageonloading (r.drawable.ic_stub)//Set the picture to be displayed during the download. Showimageforemptyuri (R.drawable.ic_empty)//Set the picture URI to be empty or wrong when the picture is displayed. Showimageonfail (r.drawable.ic_error)//Set Picture loading/ The image that is displayed when the error is in the decoding process. delaybeforeloading (1000)//Set the time delay after which the download begins. Cacheinmemory (TRUE)//sets whether the downloaded picture is in memory. Cacheondisk (TRUE)/ /Set whether the downloaded resource is slow to exist on the SD card. Considerexifparams (TRUE)//whether the JPEG image is considered as an EXIF parameter (rotate, flip). Imagescaletype (Imagescaletype.in_sample_ power_of_2)//Set How the picture is displayed in the encoding. Bitmapconfig (Bitmap.Config.RGB_565)//Set the decoding type of the picture. Displayer (New Roundedbitmapdisplayer ( 20)//Whether it is set to rounded corners, how many radians. Displayer (New Fadeinbitmapdisplayer (1000))//Whether the picture is loaded and the animation time is gradually entered. build (); @Overridepublic int GetCount () {return image_urls.length;} @Overridepublic Object getItem (int position) {return position;} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic View GetView (final int position, view ConveRtview, ViewGroup parent) {View view = convertview;final Viewholder holder;if (Convertview = = null) {view = Inflater.infla Te (R.layout.listview_item, parent, false); holder = new Viewholder (); holder.text = (TextView) View.findviewbyid ( R.id.text); holder.image = (ImageView) View.findviewbyid (r.id.image); View.settag (holder);} else {holder = (Viewholder) View.gettag ();} Holder.text.setText ("Item" + (position + 1)); Imageloader.getinstance (). DisplayImage (Image_urls[position], Holder.image, Options, Animatefirstlistener); return view;}} Static class Viewholder {TextView text;imageview image;} private static class Animatefirstdisplaylistener extends Simpleimageloadinglistener {static final list<string> Displayedimages = collections.synchronizedlist (New linkedlist<string> ()); @Overridepublic void Onloadingcomplete (String Imageuri, view view, Bitmap loadedimage) {if (loadedimage! = null) {ImageView ImageView = (Imagev Iew) View;boolean Firstdisplay =!displayedimages.contains (Imageuri);Firstdisplay) {fadeinbitmapdisplayer.animate (ImageView, $);d Isplayedimages.add (Imageuri);}}}} 

In use, mainly these fewimageloader.getinstance ().DisplayImage (),imageloader.getinstance ().LoadImage (),imageloader.getinstance ().Loadimagesync (),imageloader.getinstance ().Loadimagesync () method is synchronous, android4.0 has a feature, network operation cannot be in the main thread, soimageloader.getinstance ().Loadimagesync () method We are not going to use it.

The main introduction is imageloader.getinstance (). DisplayImage () Three of these overloaded methods:

(1). Imageloader.getinstance (). DisplayImage (ImageUrl, ImageView): Where the parameter imageUrl represents the URL address of the picture, ImageView represents the ImageView control that hosts the picture

(2). imageloader.getinstance (). DisplayImage (ImageUrl, imageview,options): Where the parameter imageUrl represents the URL address of the picture, ImageView represents the ImageView control that hosts the picture, and the options represents the Displayimageoptions configuration file

(3). Imageloader.getinstance (). DisplayImage (Image_urls[position], holder.image, Options, Animatefirstlistener): This is one of the methods used in the above code. animatefirstlistener Picture loading monitor.

Picture Download Monitor also can use Imageloadinglistener, this way is more complex, can use simple point of simpleimageloadinglistener.

New Imageloadinglistener () {@Overridepublic void onloadingcancelled (String arg0, View arg1) {///load Cancel when execute  }@ overridepublic void Onloadingcomplete (String arg0, View arg1,bitmap arg2) {//Load successful execution  } @Overridepublic void Onloadingfailed (String arg0, View Arg1,failreason arg2) {//load failed when execute} @Overridepublic void onloadingstarted (String arg0 , View arg1) {//Start loading execution}  };

Three. Load images from other sources:

String Imageuri = "Http://site.com/image.png"; From webstring Imageuri = "File:///mnt/sdcard/image.png"; From SD cardstring Imageuri = "CONTENT://MEDIA/EXTERNAL/AUDIO/ALBUMART/13"; From content providerstring Imageuri = "Assets://image.png"; From assetsstring Imageuri = "drawable://" + r.drawable.image; From Drawables (only images, Non-9patch)

Four. Avoid oom (I also learned from someone else's blog, paste the great God blog address http://blog.csdn.net/xiaanming/article/details/26810303):

1. Minus The number of threads in a small thread pool, configured in Imageloaderconfiguration (. ThreadPoolSize), is recommended for configuration 1-5.

2. In The Displayimageoptions option is configured with Bitmapconfig as Bitmap.Config.RGB_565, because the default is argb_8888, and using rgb_565 will consume twice times less memory
3 than argb_8888. The memory cache for the configuration picture in Imageloaderconfiguration is MemoryCache (new Weakmemorycache ()) or does not use the memory cache
4. Set the. Imagescaletype (Imagescaletype.in_sample_int) or Imagescaletype (ImageScaleType.EXACTLY) in the displayimageoptions option.
through these, I believe you have a very good understanding of the use of the Universal-image-loader framework, When we use this framework, we try to use the DisplayImage () method to load the image, and LoadImage () is the Onloadingcomplete () method that recalls the picture object to the Imageloadinglistener interface. Need us to manually set up to ImageView above, DisplayImage () method, the ImageView object uses weak references, convenient garbage collector to reclaim ImageView objects, if we want to load fixed-size images, Using the LoadImage () method requires passing a ImageSize object, and the DisplayImage () method is based on the measured value of the ImageView object, or Android:layout_width and Android:layout_ Height setting value, or Android:maxwidth and/or android:maxheight set value to crop the picture










Android Universal-image-loader Framework Learning

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.