編輯:關於 Android 程式設計
在 Android 上處理網路圖片一向麻煩:下載、解碼、顯示、回收,任一環節出錯就可能 OOM。Universal Image Loader(UIL)就是為了解決這一整串問題而生,它源自 Fedor Vlasov 的專案,經過大幅重構後成為 GitHub 上相當知名的開源庫。
ImageLoader 是單例,用 getInstance() 取得。使用前必須先初始化設定,否則會丟出 IllegalStateException:
//創建默認的ImageLoader配置參數 ImageLoaderConfiguration configuration = ImageLoaderConfiguration .createDefault(this); //Initialize ImageLoader with configuration. ImageLoader.getInstance().init(configuration);
因為是單例,整個 App 只需初始化一次,建議放在 Application 或第一個 Activity 的 onCreate 中;重複初始化不會有效果。透過 ImageLoaderConfiguration.Builder 可以細調各項參數:
File cacheDir =StorageUtils.getOwnCacheDirectory(this, "imageloader/Cache"); ImageLoaderConfigurationconfig = new ImageLoaderConfiguration .Builder(this) .memoryCacheExtraOptions(480, 800) // maxwidth, max height,即保存的每個緩存文件的最大長寬 .threadPoolSize(3)//線程池內加載的數量 .threadPriority(Thread.NORM_PRIORITY -2) .denyCacheImageMultipleSizesInMemory() .memoryCache(new UsingFreqLimitedMemoryCache(2* 1024 * 1024)) // You can pass your own memory cache implementation/你可以通過自己的內存緩存實現 .memoryCacheSize(2 * 1024 * 1024) .discCacheSize(50 * 1024 * 1024) .discCacheFileNameGenerator(newMd5FileNameGenerator())//將保存的時候的URI名稱用MD5 加密 .tasksProcessingOrder(QueueProcessingType.LIFO) .discCacheFileCount(100) //緩存的文件數量 .discCache(new UnlimitedDiscCache(cacheDir))//自定義緩存路徑 .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) .imageDownloader(new BaseImageDownloader(this,5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超時時間 .writeDebugLogs() // Remove for releaseapp .build();//開始構建 ImageLoader.getInstance().init(config);
實務上要特別注意 threadPoolSize:設太大反而增加 OOM 風險,官方建議落在 1 到 5 之間。memoryCacheExtraOptions 則是用來告訴 UIL 你的 ImageView 大概會有多大,讓它預留合理的解碼緩衝。
ImageLoader imageLoader = ImageLoader.getInstance();
顯示前先建立 DisplayImageOptions,決定載入中、失敗、空 URI 時的佔位圖,以及是否啟用雙緩存:
DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.ic_stub) //加載圖片時的圖片 .showImageForEmptyUri(R.drawable.ic_empty) //沒有圖片資源時的默認圖片 .showImageOnFail(R.drawable.ic_error) //加載失敗時的圖片 .cacheInMemory(true) //啟用內存緩存 .cacheOnDisk(true) //啟用外存緩存 .considerExifParams(true) //啟用EXIF和JPEG圖像格式 .displayer(new RoundedBitmapDisplayer(20)) //設置顯示風格這裡是圓角矩形 .build();
以下是 DisplayImageOptions 全部的預設欄位,可依需求自行覆寫:
private int imageResOnLoading = 0; private int imageResForEmptyUri = 0; private int imageResOnFail = 0; private Drawable imageOnLoading = null; private Drawable imageForEmptyUri = null; private Drawable imageOnFail = null; private boolean resetViewBeforeLoading = false; private boolean cacheInMemory = false; private boolean cacheOnDisk = false; private ImageScaleType imageScaleType = ImageScaleType.IN_SAMPLE_POWER_OF_2; private Options decodingOptions = new Options(); private int delayBeforeLoading = 0; private boolean considerExifParams = false; private Object extraForDownloader = null; private BitmapProcessor preProcessor = null; private BitmapProcessor postProcessor = null; private BitmapDisplayer displayer = DefaultConfigurationFactory.createBitmapDisplayer(); private Handler handler = null; private boolean isSyncLoading = false;
想加上淡入效果或進度條,就實作 ImageLoadingListener。下面這個寫法用一個靜態清單記住哪些 URI 已經播放過動畫,避免捲動時重複閃動:
ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener(); private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener { static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>()); @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (loadedImage != null) { ImageView imageView = (ImageView) view; boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 500); displayedImages.add(imageUri); } } } }
然後一行就能載入:
imageLoader.displayImage(imageUrl, imageview, options, animateFirstListener);
本地圖片要在絕對路徑前加上 file://,網路圖片直接寫 URL。不同來源的寫法如下:
String imageUri = "https://site.com/image.png"; // 網絡圖片 String imageUri = "file:///mnt/sdcard/image.png"; //SD卡圖片 String imageUri = "content://media/external/audio/albumart/13"; // 媒體文件夾 String imageUri = "assets://image.png"; // assets String imageUri = "drawable://" + R.drawable.image; // drawable文件
可以放在 Activity 的 onDestroy,也可以做成設定頁讓使用者自行決定:
@Override public void onDestroy() { super.onDestroy(); imageLoader.clearMemoryCache(); imageLoader.clearDiskCache(); }
長列表快速滑動時,載入非當前畫面的圖片純屬浪費。UIL 提供了 PauseOnScrollListener,用代理模式攔住捲動事件:
listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling)); gridView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));
第一個參數是 ImageLoader,第二個控制「滑動中是否暫停」,第三個控制「快速甩動時是否暫停」。一般建議兩者都傳 true。
UIL 對 OutOfMemoryError 做了 catch,能避免直接 crash,但如果頻繁發生就該從設定下手:
threadPoolSize,建議 1 到 5。bitmapConfig 設為 Bitmap.Config.RGB_565,相比預設的 ARGB_8888 可省下約一半記憶體(代價是沒有 alpha 通道)。memoryCache(new WeakMemoryCache()) 或直接關閉記憶體緩存。imageScaleType 為 IN_SAMPLE_INT 或 EXACTLY。建議優先用 displayImage()。它對 ImageView 使用弱引用,方便 GC 回收,而且會依 ImageView 的測量值或 layout_width/height、maxWidth/maxHeight 自動裁切圖片。相對地,loadImage() 只是把 Bitmap 透過 onLoadingComplete() 回呼給你,需要自己 setImageBitmap,而且要明確傳入 ImageSize 才能控制解碼尺寸。除非你有特殊需求(例如預先下載但不立刻顯示),否則用 displayImage 更省心。
Android 四大視圖動畫詳解:Alpha、Translate、Rotate 與 Scale
Android 的動畫體系主要分為視圖動畫(View Animation)、屬性動畫(Property Animation)與 Drawable 動畫三大類。本文聚焦最古
Android MediaPlayer 實現本地音樂播放器:綁定 Service 的完全示例
用 MediaPlayer 做一個本地音樂播放器並不難,難的是「播放不能停」。當用戶按了 Home 鍵,Activity 進入後台,如果播放邏輯寫在 Activity 裡
RecyclerView 局部刷新踩坑全記錄:payload 參數才是正解
WeTest 導讀 用過 RecyclerView 的人都知道它比 ListView 靈活得多,但坑也埋得同樣深。本文是騰訊開發工程師的一次實戰記錄:一個看似簡單的「點擊
Android 組件化開發(2):用 GridView 實作網格布局的 RadioButton 矩陣
前言 一般我們用 RadioGroup 包住一批 RadioButton,就能拿到「單選互斥」的效果,省心省力。問題是 RadioGroup 骨子裡只是一個耿直的 Lin