加载图片的开源库com.nostra13.universalimageloader,非常好用,github上目前最新版应该是1.9.x了。很多android项目都在用。
1、报错问题 在Adt22
com.nostra13.universalimageloader.core.ImageLoaderConfiguration
2、详细分析参考http://www.cnblogs.com/osmondy/p/3266023.html
3、代码例子下载https://github.com/nostra13/Android-Universal-Image-Loader
4、详细如下
Image Loader for Android
This project aims to provide a reusable instrument for asynchronous
image loading, caching and displaying. It is originally based
on
Vlasov’s project
refactored and improved since then.
Features
- Multithread image loading
- Possibility of wide tuning ImageLoader’s configuration (thread
executors, downlaoder, decoder, memory and disc cache, display
image options, and others)
- Possibility of image caching in memory and/or on device’s file
sysytem (or SD card)
- Possibility to “listen” loading process
- Possibility to customize every display image call with
separated options
- Widget support
Android 2.0+ support
Downloads
- universal-image-loader-1.8.6.jar
(library;
contains *.class files)
- universal-image-loader-1.8.6-sources.jar
(sources;
contains *.java files)
- universal-image-loader-1.8.6-javadoc.jar
(Java
docs; contains *.html files)
- universal-image-loader-1.8.6-with-sources.jar
(library
with sources inside; contains *.class and *.java files)
Prefer to use this JAR so you can see Java docs in Eclipse
tooltips.
- universal-image-loader-sample-1.8.6.apk
(sample
application)
Latest snapshot of the library –
Documentation*
- Universal Image Loader. Part 1 – Introduction [RU
| EN]
- Universal Image Loader. Part 2 – Configuration [RU
| EN]
- Universal Image Loader. Part 3 – Usage [RU
| EN]
(*) a bit outdated
Changelog
User Support
- Look into
Useful
Info
- Search problem solution on
StackOverFlow
- Ask your own question on
StackOverFlow.
Be sure to mention following information in your question:
- UIL version (e.g. 1.8.6)
- Android version tested on (e.g. 2.1)
- your configuration (
ImageLoaderConfiguration
)
- display options (
DisplayImageOptions
)
getView()
you use it)
- XML layout of your ImageView you load image into
Bugs
requests
If you have some
migration
sure to ask for help
Quick Setup
1. Include library
Manual:
- Download
JAR
- Put the JAR in
the
of your Android project
or
Maven dependency:
com.nostra13.universalimageloader
universal-image-loader
1.8.6
2. Android Manifest
android:name=“android.permission.INTERNET” />
android:name=“android.permission.WRITE_EXTERNAL_STORAGE” />
…
android:name=“MyApplication”>
…
3. Application class
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Create global configuration and initialize ImageLoader with this configuration
ImageLoaderConfiguration
…
.build();
ImageLoader.getInstance().init(config);
}
}
Configuration and
Display Options
- ImageLoader
Configuration
(ImageLoaderConfiguration
)
is global
- Display Options (
DisplayImageOptions
)
are local
(ImageLoader.displayImage(...)
).
Configuration
All options in Configuration builder are optional. Use only those
you really want to customize.
See default values for config options in Java docs for every
option.
// DON’T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration
.memoryCacheExtraOptions(480, 800) // default = device screen dimensions
.discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null)
.taskExecutor(…)
.taskExecutorForCachedIma
.threadPoolSize(3) // default
.threadPriority(Thread.NORM_PRIORITY – 1) // default
.tasksProcessingOrder(QueueProcessingType.FIFO) // default
.denyCacheImageMultipleSi
.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
.memoryCacheSize(2 * 1024 * 1024)
.memoryCacheSizePercentag
.discCache(new UnlimitedDiscCache(cacheDir)) // default
.discCacheSize(50 * 1024 * 1024)
.discCacheFileCount(100)
.discCacheFileNameGenerat
.imageDownloader(new BaseImageDownloader(context)) // default
.imageDecoder(new BaseImageDecoder()) // default
.defaultDisplayImageOptio
.writeDebugLogs()
.build();
Display Options
Display Options can be applied to every display task (ImageLoader.displayImage(...)
Note:
passed to ImageLoader.displayImage(...)
method
then default Display Options from configuration (ImageLoaderConfiguration
)
will be used.
// DON’T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub) // resource or drawable
.showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable
.showImageOnFail(R.drawable.ic_error) // resource or drawable
.resetViewBeforeLoading(false) // default
.delayBeforeLoading(1000)
.cacheInMemory(false) // default
.cacheOnDisc(false) // default
.preProcessor(…)
.postProcessor(…)
.extraForDownloader(…)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
.bitmapConfig(Bitmap.Config.ARGB_8888) // default
.decodingOptions(…)
.displayer(new SimpleBitmapDisplayer()) // default
.handler(new Handler()) // default
.build();
Usage
Acceptable URIs examples
String imageUri = “http://site.com/image.png”; // from Web
String imageUri = “file:///mnt/sdcard/image.png”; // from SD card
String imageUri = “content://media/external/audio/albumart/13”; // from content provider
String imageUri = “assets://image.png”; // from assets
String imageUri = “drawable://” + R.drawable.image; // from drawables (only images, non-9patch)
NOTE: drawable://
if you really need it! Always
native way
–ImageView.setImageResource(...)
of using of ImageLoader
.
Simple
// Load image, decode it to Bitmap and display Bitmap in ImageView
imageLoader.displayImage(imageUri, imageView);
// Load image, decode it to Bitmap and return Bitmap to callback
imageLoader.loadImage(imageUri, new SimpleImageLoadingListen
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// Do whatever you want with Bitmap
}
});
Complete
// Load image, decode it to Bitmap and display Bitmap in ImageView
imageLoader.displayImage(imageUri, imageView, displayOptions, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
…
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
…
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
…
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
…
}
});
// Load image, decode it to Bitmap and return Bitmap to callback
ImageSize targetSize = new ImageSize(120, 80); // result Bitmap will be fit to this size
imageLoader.loadImage(imageUri, targetSize, displayOptions, new SimpleImageLoadingListen
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// Do whatever you want with Bitmap
}
});
ImageLoader Helpers
Other useful methods and classes to consider.
ImageLoader |
| – getMemoryCache()
| – clearMemoryCache()
| – getDiscCache()
| – clearDiscCache()
| – denyNetworkDownloads(boolean)
| – handleSlowNetwork(boolean)
| – pause()
| – resume()
| – stop()
| – destroy()
| – getLoadingUriForView(ImageView)
| – cancelDisplayTask(ImageView)
MemoryCacheUtil |
| – findCachedBitmapsForImag
| – findCacheKeysForImageUri
| – removeFromCache(…)
DiscCacheUtil |
| – findInCache(…)
| – removeFromCache(…)
StorageUtils |
| – getCacheDirectory(Context)
| – getIndividualCacheDirect
| – getOwnCacheDirectory(Context, String)
PauseOnScrollListener
Also look into more detailed
Map
Useful Info
Caching is NOT enabled by
default.
be cached in memory and/or on disc then you should enable caching
in DisplayImageOptions this way:
// Create default options which will be used for every
// displayImage(…) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
…
.cacheInMemory(true)
.cacheOnDisc(true)
…
.build();
ImageLoaderConfiguration
…
.defaultDisplayImageOptio
…
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
// Then later, when you want to display image
ImageLoader.getInstance().displayImage(imageUrl, imageView); // Default options will be used
or this way:
DisplayImageOptions options = new DisplayImageOptions.Builder()
…
.cacheInMemory(true)
.cacheOnDisc(true)
…
.build();
ImageLoader.getInstance().displayImage(imageUrl, imageView, options); // Incoming options will be used
If you enabled disc caching then UIL
try to cache images on external storage
(/sdcard/Android/data/[package_name]/cache). If external storage is
not available then images are cached on device’s filesytem. To
provide caching on external storage (SD card) add following
permission to AndroidManifest.xml:
<</span>uses–permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE”/>
How UIL define Bitmap size needed for
exact ImageView? It searches defined parameters:
- Get actual measured width and height of ImageView
- Get
android:layout_width
and android:layout_height
parameters
- Get
android:maxWidth
and/or android:maxHeight
parameters
- Get maximum width and/or height parameters from configuration
(memoryCacheExtraOptions(int,
int)
- Get width and/or height of device screen
So
set android:layout_width
|android:layout_height
android:maxWidth
|android:maxHeight
for ImageView if you know approximate maximum size of it. It will
help correctly compute Bitmap size needed for this view
and
If you often
got
your app using Universal Image Loader then try next (all of them or
several):
- Reduce thread pool size in configuration (
.threadPoolSize(...)
).
1 – 5 is recommended.
- Use
.bitmapConfig(Bitmap.Config.RGB_565)
in
display options. Bitmaps in RGB_565 consume 2 times less memory
than in ARGB_8888.
- Use
.memoryCache(new
WeakMemoryCache())
disable caching in memory at all in display options (don’t
call .cacheInMemory()
).
- Use
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
in
display options. Or try.imageScaleType(ImageScaleType.EXACTLY)
.
- Avoid using RoundedBitmapDisplayer. It creates new Bitmap
object with ARGB_8888 config for displaying during work.
For memory cache configuration
(ImageLoaderConfiguration
)
you can use already prepared implementations.
- Cache using
only
strong
LruMemoryCache
is deleted when cache size limit is exceeded) –Used by
default for API >= 9
- Caches using
weak and
strong
UsingFreqLimitedMemoryCa
frequently used bitmap is deleted when cache size limit is
exceeded)
LRULimitedMemoryCache
bitmap is deleted when cache size limit is exceeded)
–
9
FIFOLimitedMemoryCache
for deletion when cache size limit is exceeded)
LargestLimitedMemoryCach
bitmap is deleted when cache size limit is exceeded)
LimitedAgeMemoryCache
object is deleted when its age exceeds defined value)
- Cache using
only
weak
WeakMemoryCache
For disc cache configuration
(ImageLoaderConfiguration
)
you can use already prepared implementations:
UnlimitedDiscCache
doesn’t limit cache size) –
default
TotalSizeLimitedDiscCach
total cache size. If cache size exceeds specified limit then file
with the most oldest last usage date will be deleted)
FileCountLimitedDiscCach
file count. If file count in cache directory exceeds specified
limit then file with the most oldest last usage date will be
deleted. Use it if your cached files are of about the same
size.)
LimitedAgeDiscCache
with limited files’ lifetime. If age of cached file exceeds defined
limit then it will be deleted from cache.)
NOTE:
30%-faster than other limited disc cache implementations.
To display bitmap (DisplayImageOptions.displayer(...)
)
you can use already prepared implementations:
RoundedBitmapDisplayer
with rounded corners)
FadeInBitmapDisplayer
“fade in” animation)
To avoid list (grid, …) scrolling
lags you can use PauseOnScrollListener
:
boolean pauseOnScroll = false; // or true
boolean pauseOnFling = true; // or false
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);
listView.setOnScrollListener(liste