欢迎来到 Android人的问与答 ,在这里提问或帮助他人解答。 Question2Answer的1.6.x和1.7.x版本的中文翻译包我修改更新:

Question2answer

如何使用中文语言包

Q2A 1.6.x - Chinese Simplified (简体中文)

Q2A 1.7.x - Chinese Simplified (简体中文)


国内服务器推荐 阿里云服务器
国外服务器推荐 DigitalOcean
VPN推荐 正版Green VPN
阿里云推荐码:ldvq50

Android异步网络加载图片的控件

0 喜欢 0 不喜欢
398 浏览

https://github.com/nostra13/Android-Universal-Image-Loader

 

Universal Image Loader for Android

 

This project aims to provide a reusable instrument for asynchronous image loading, caching and displaying. It is originally based on Fedor Vlasov's project and has been vastly refactored and improved since then.

 

Features

  • Multithread image loading
  • Possibility of wide tuning ImageLoader's configuration (thread pool size, HTTP options, 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

 

 

Usage

Simple

ImageView imageView = ...

String imageUrl = "http://site.com/image.png"; // or "file:///mnt/sdcard/images/image.jpg"

 

// Get singletone instance of ImageLoader

ImageLoader imageLoader = ImageLoader.getInstance();

// Initialize ImageLoader with configuration. Do it once.

imageLoader.init(ImageLoaderConfiguration.createDefault(context));

// Load and display image asynchronously

imageLoader.displayImage(imageUrl, imageView);

Most detailed

ImageView imageView = ...

String imageUrl = "http://site.com/image.png"; // or "file:///mnt/sdcard/images/image.jpg"

ProgressBar spinner = ...

File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "UniversalImageLoader/Cache");

 

// Get singletone instance of ImageLoader

ImageLoader imageLoader = ImageLoader.getInstance();

// Create configuration for ImageLoader (all options are optional, use only those you really want to customize)

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())

            .memoryCacheExtraOptions(480, 800) // max width, max height

            .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75) // Can slow ImageLoader, use it carefully (Better don't use it)

            .threadPoolSize(3)

            .threadPriority(Thread.NORM_PRIORITY - 1)

            .denyCacheImageMultipleSizesInMemory()

            .offOutOfMemoryHandling()

            .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation

            .discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation

            .discCacheFileNameGenerator(new HashCodeFileNameGenerator())

            .imageDownloader(new URLConnectionImageDownloader(5 * 1000, 20 * 1000)) // connectTimeout (5 s), readTimeout (20 s)

            .defaultDisplayImageOptions(DisplayImageOptions.createSimple())

            .enableLogging()

            .build();

// Initialize ImageLoader with created configuration. Do it once on Application start.

imageLoader.init(config);

 

 

最新提问 1月 18, 2015 分类:Android网络通信 | 用户: forlong401 (7,050 分)

1个回答

0 喜欢 0 不喜欢

// Creates display image options for custom display task (all options are optional)

DisplayImageOptions options = new DisplayImageOptions.Builder()

           .showStubImage(R.drawable.stub_image)

           .showImageForEmptyUri(R.drawable.image_for_empty_url)

           .cacheInMemory()

           .cacheOnDisc()

           .imageScaleType(ImageScaleType.POWER_OF_2)

           .displayer(new RoundedBitmapDisplayer(0xff424242, 20))

           .build();

// Load and display image

imageLoader.displayImage(imageUrl, imageView, options, new ImageLoadingListener() {

    @Override

    public void onLoadingStarted() {

       spinner.show();

    }

    @Override

    public void onLoadingFailed(FailReason failReason) {

        spinner.hide();

    }

    @Override

    public void onLoadingComplete(Bitmap loadedImage) {

        spinner.hide();

    }

    @Override

    public void onLoadingCancelled() {

        // Do nothing

    }

});

 

最新回答 1月 18, 2015 用户: forlong401 (7,050 分)
Useful info

Caching is NOT enabled by default. If you want loaded images will 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()
        .cacheOnDisc()
        ...
        .build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
        ...
        .defaultDisplayImageOptions(defaultOptions)
        ...
        .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()
        .cacheOnDisc()
        ...
        .build();
ImageLoader.getInstance().displayImage(imageUrl, imageView, options); // Incoming options will be used

How UIL define Bitmap size needed for exact ImageView? Search defined parameters top-down:
Get android:layout_width or android:layout_height parameters
Get android:maxWidth and android:maxHeight parameters
Get maximum size parameters from configuration (memoryCacheExtraOptions(int, int) option)
Set android:layout_width|android:layout_height or android:maxWidth|android:maxHeight parameters for ImageView if you know approximate maximum size of it. It will help correctly compute Bitmap size needed for this view and save memory.
If you often got OutOfMemoryError in your app using Universal Image Loader then try set WeakMemoryCache into configuration:
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
        ...
        .memoryCache(new WeakMemoryCache())
        ...
        .build();

For memory cache configuration (ImageLoaderConfiguration.Builder.memoryCache(...)) you can use already prepared implementations:
UsingFreqLimitedMemoryCache (The least frequently used bitmap is deleted when cache size limit is exceeded) - Used by default
LRULimitedMemoryCache (Least recently used bitmap is deleted when cache size limit is exceeded)
FIFOLimitedMemoryCache (FIFO rule is used for deletion when cache size limit is exceeded)
LargestLimitedMemoryCache (The largest bitmap is deleted when cache size limit is exceeded)
LimitedAgeMemoryCache (Decorator. Cached object is deleted when its age exceeds defined value)
WeakMemoryCache (Memory cache with only weak references to bitmaps)
For disc cache configuration (ImageLoaderConfiguration.Builder.discCache(...)) you can use already prepared implementations:
UnlimitedDiscCache (The fastest cache, doesn't limit cache size) - Used by default
TotalSizeLimitedDiscCache (Cache limited by total cache size. If cache size exceeds specified limit then file with the most oldest last usage date will be deleted)
FileCountLimitedDiscCache (Cache limited by 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 (Size-unlimited cache with limited files' lifetime. If age of cached file exceeds defined limit then it will be deleted from cache.)
NOTE: UnlimitedDiscCache is 30%-faster than other limited disc cache implementations.
...