ImageLoader works with ImageSwitcher and imageloader

Source: Internet
Author: User

ImageLoader works with ImageSwitcher and imageloader

First initialize ImageLoader in MyApplication

initImageLoader(getApplicationContext());
/*** Initialize ImageLoader * If you often see oom * to reduce the size of the configured thread pool (. threadPoolSize (...), we recommend that you use 1 ~ 5 * Used in configuration. diskCacheExtraOptions (480,320, null) * @ param context */public static void initImageLoader (Context context) {// This configuration tuning is custom. you can tune every option, you may tune some of them, // or you can create default configuration by // ImageLoaderConfiguration. createDefault (this); // method. imageLoaderConfiguration config = new ImageLoaderConfiguration. builder (context ). threadPriority (Thread. NORM_PRIORITY-1 ). threadPoolSize (5 ). denyCacheImageMultipleSizesInMemory (). discCacheFileNameGenerator (new Md5FileNameGenerator ()). discCacheSize (100*1024*1024 ). tasksProcessingOrder (QueueProcessingType. LIFO )//. enableLogging () // Not necessary in common. build (); // Initialize ImageLoader with configuration. myImageLoader. getInstance (). init (config );}

 

 

Create an imageLoader and set parameters in BaseActivity.

protected MyImageLoader imageLoader = MyImageLoader.getInstance();

 

/*** If oom * is frequently used to disable cacheInMemory (false) caching in the memory, * use it in the display options. bitmapConfig (Bitmap. config. RGB_565 ). the RGB_565 mode consumes twice less memory than the ARGB_8888 mode. * Used in configuration. memoryCache (newWeakMemoryCache () or completely disable the cache in the memory (don't call. cacheInMemory ()). * Used in display options. imageScaleType (ImageScaleType. EXACTLY) or. imageScaleType (ImageScaleType. IN_SAMPLE_INT) * You must initialize ImageLoaderConfiguration. Otherwise, an error will be reported * after cache is enabled, it will be cached to the following external SD card address by default (/sdcard/Android/data/[package_name]/cache ). if the external SD card does not exist, it will be cached to the mobile phone. the cached data to the SD card must be stored in AndroidManifest. configure WRITE_EXTERNAL_STORAGE */protected DisplayImageOptions options = new DisplayImageOptions in the xml file. builder ()//. resetViewBeforeLoading ()//. showImageOnLoading (R. drawable. ic_stub) // attach the image to display //. showImageOnFail (R. drawable. ic_error) // the image that fails to be loaded //. cacheInMemory (). cacheOnDisc () // sets whether the downloaded image is cached in the SD card. // The downloaded image is cached in/mnt/shell/emulated/0/Android/data/com. sdmc. hotel. ollauncher/cache/uil-images. imageScaleType (ImageScaleType. IN_SAMPLE_INT) // sets how the image is encoded (an integer multiple of the image to be sampled twice ). bitmapConfig (Bitmap. config. RGB_565) // 16 R 5G 6 B 5 no transparency ()//. displayer (new FadeInBitmapDisplayer (500) // sets the time when the image is gradually displayed. build ();

 

 

How to use in the activity to be used

imageLoader.displayImage(this, path, (ImageView) mImageSwitcher.getCurrentView(),                         options, mImageLoadingListener);
imageLoader.loadImage(this, path,                         options, mImageLoadingListener);

Add a listener.

/*** After loading the imageUri into a bitmap, the listener is triggered. * then, the loaded bitmap is added to SparseArray <SoftReference <Bitmap> * before imageUri = file: /// data/user/0/com. sdmc. hotel. ollauncher/files/cloud/public/upload/picture/users * after path =/public/upload/picture/users * hashCode =-1524414597 */private SimpleImageLoadingListener mImageLoadingListener = new SimpleImageLoadingListener () {@ Override public void onLoadingComplete (String imageUri, View, Bitmap loadedImage) {String path = imageUri. substring (imageUri. indexOf (Configs. getaskproj (mContext) + Configs. getmediaproj (mContext ). length (); log ("before imageUri =" + imageUri + "; getaskproj" + Configs. getmediaproj (mContext); log ("after path =" + path + "; hashCode =" + path. hashCode (); mLoadedImages. append (path. hashCode (), new SoftReference <Bitmap> (loadedImage ));}};

And a soft-referenced SparseArray

// SparseArray replaces HashMap, SoftReference soft connection private SparseArray <SoftReference <Bitmap> mLoadedImages = new SparseArray <SoftReference <Bitmap> ();

 

And the MyImageLoader class.

/*** Copyright (c) 2003-2013 Shenzhen SDMC Technology Co ., LTD * All Rights Reserved. ** Filename: MyImageLoader. java * Author: wuxiaodi * Creation time: 2:01:58 pm-2013-7-17 * Description: */package com. sdmc. hotel. util; import java. io. file; import android. content. context; import android. widget. imageView; import com. nostra13.universalimageloader. core. displayImageOptions; import com. nostra13.universalimageloader. core. imageLoader; import com. nostra13.universalimageloader. core. assist. imageLoadingListener; import com. nostra13.universalimageloader. core. assist. imageSize;/*** Just to cache images in our archive, so to use it when off-line. */public class MyImageLoader extends ImageLoader {private static MyImageLoader instance; public static MyImageLoader getInstance () {if (instance = null) {synchronized (MyImageLoader. class) {if (instance = null) {instance = new MyImageLoader () ;}} return instance ;}protected MyImageLoader () {} public void displayImage (Context context, string path, ImageView imageView) {String furi = getLocalImage (context, path); if (furi = null) {super. displayImage (Configs. getServerAddress (context) + path, imageView);} else {super. displayImage (furi, imageView) ;}} public void displayImage (Context context, String path, ImageView imageView, DisplayImageOptions options) {String furi = getLocalImage (context, path ); if (furi = null) {super. displayImage (Configs. getServerAddress (context) + path, imageView, options);} else {super. displayImage (furi, imageView, options) ;}} public void displayImage (Context context, String path, ImageView imageView, ImageLoadingListener listener) {String furi = getLocalImage (context, path ); if (furi = null) {super. displayImage (Configs. getServerAddress (context) + path, imageView, listener);} else {super. displayImage (furi, imageView, listener) ;}}/*** in the displayImage () method, Weak references are used for ImageView objects. * This facilitates the Garbage Collector to recycle ImageView objects, if we want to load a fixed-size image, * use the loadImage () method to pass an ImageSize object, while the displayImage () method will be based on the * measurement value of the ImageView object, or android: layout_width and android: layout_height value, * or android: maxWidth and/or android: maxHeight value to crop the image * crop Bitmap based on the size of the control (ImageView, reduces Bitmap memory usage * @ param context * @ param path * @ param imageView * @ param options * @ param listener */public void displayImage (Context context, String path, imageView imageView, DisplayImageOptions options, ImageLoadingListener) {String furi = getLocalImage (context, path); if (furi = null) {// log ("furi1:" + Configs. getServerAddress (context) + path + "; imageView" + imageView + "; options" + options + "; listener" + listener); super. displayImage (Configs. getServerAddress (context) + path, imageView, options, listener);} else {// furi2: file: // data/com. sdmc. hotel. ollauncher/files/cloud/public/upload/picture/1441178355.jpg; imageViewandroid. widget .; optionscom. nostra13.; listenercom. sdmc // log ("furi2:" + furi + "; imageView" + imageView + "; options" + options + "; listener" + listener); super. displayImage (furi, imageView, options, listener) ;}}/*** displayImage is more convenient * use the loadImage () method of ImageLoader to load network images * loadImage () callback the image object to the onLoadingComplete () method of the ImageLoadingListener interface, * You need to manually set it to the ImageView * @ param context * @ param path * @ param listener */public void loadImage (Context context, String path, ImageLoadingListener listener) {String furi = getLocalImage (context, path); if (furi = null) {super. loadImage (Configs. getServerAddress (context) + path, listener);} else {super. loadImage (furi, listener) ;}}/*** displayImage is more convenient * What should we do if we want to specify the image size, specify the image width and height. The Code is as follows * @ param context * @ param path * @ param minImageSize ImageSize mImageSize = new ImageSize (100,100 ); * @ param listener */public void loadImage (Context context, String path, ImageSize minImageSize, ImageLoadingListener listener) {String furi = getLocalImage (context, path); if (furi = null) {super. loadImage (Configs. getServerAddress (context) + path, minImageSize, listener);} else {super. loadImage (furi, minImageSize, listener) ;}} public void loadImage (Context context, String path, DisplayImageOptions options, ImageLoadingListener listener) {String furi = getLocalImage (context, path ); if (furi = null) {super. loadImage (Configs. getServerAddress (context) + path, options, listener);} else {super. loadImage (furi, options, listener) ;}} public void loadImage (Context context, String path, ImageSize targetImageSize, DisplayImageOptions options, ImageLoadingListener listener) {String furi = getLocalImage (context, path); if (furi = null) {super. loadImage (Configs. getServerAddress (context) + path, targetImageSize, options, listener);} else {super. loadImage (furi, targetImageSize, options, listener) ;}} private String getLocalImage (Context context, String path) {File imagefile = new File (Configs. getCacheDir (context) + path); if (imagefile. exists () {return "file: //" + imagefile. getAbsolutePath () ;}else {return null ;}// private void log (String msg) {// LogUtil.info (this. getClass (), this + ":" + msg, "I ");////}}

 

 

 

 

 

 

 

 

 

It is also convenient to use ImageSwitcher. Create an ImageSwitcher first.

private ImageSwitcher createImageSwitcher(JsonReader reader) {        ImageSwitcherLayoutParams params = new Gson().fromJson(reader,                ImageSwitcherLayoutParams.class);        mImageSwitcher = new ImageSwitcher(this);        mImageSwitcher.setFactory(this);        AlphaAnimation inAnim = new AlphaAnimation(0, 1);        inAnim.setDuration(300);        mImageSwitcher.setInAnimation(inAnim);        AlphaAnimation outAnim = new AlphaAnimation(1, 0);        outAnim.setDuration(400);        mImageSwitcher.setOutAnimation(outAnim);        AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(                params.width, params.height, params.x, params.y);        mImageSwitcher.setLayoutParams(lp);        return mImageSwitcher;    }

 

Then implement the implements ViewFactory interface and override the makeView method.

@Override    public View makeView() {        ImageView imageView = new ImageView(this);        imageView.setScaleType(ScaleType.FIT_XY);        imageView.setLayoutParams(new ImageSwitcher.LayoutParams(                ImageSwitcher.LayoutParams.MATCH_PARENT,                 ImageSwitcher.LayoutParams.MATCH_PARENT));        return imageView;    }

 

Related Article

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.