編輯:關於 Android 程式設計
寫 Android 應用的時候幾乎繞不開圖片。問題在於,圖片的實際尺寸往往遠大於我們真正需要的顯示尺寸——相機拍出來的照片分辨率可能是屏幕的十幾倍。而每個應用程序的可用內存都是有限的,一次性加載過多過大的 Bitmap,OOM(OutOfMemoryError)就是必然結果。
需求很簡單:一個 ListView,每個條目展示一張圖片。
主頁面布局
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
條目布局
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="100dp" />
</LinearLayout>
如果 getView 裡直接這樣寫:
imageView.setImageResource(R.drawable.girl);
那麼系統會按原圖尺寸把整張高清圖片解碼進內存。模擬器上跑起來的結果是:能顯示,但滑動卡到幾乎拖不動。

原因其實一眼就能看出來:我們根本不需要那麼大的圖。既然如此,把圖片壓縮到 100×100 去顯示就好。
核心 API 是 BitmapFactory.decodeResource(Resources res, int id, BitmapFactory.Options opts),配合 BitmapFactory.Options 來控制解碼行為。
關鍵技巧是 inJustDecodeBounds:把它置為 true 時,解碼過程不會為 Bitmap 分配任何內存,返回值是 null,但 Options 裡的 outWidth、outHeight、outMimeType 會被正確填充。這就讓我們能在真正加載之前先「看一眼」原圖尺寸,再決定採樣率。
public static Bitmap decodeSampleBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// 第一次解析:只讀取邊界信息,不分配內存
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 根據目標尺寸計算合適的採樣率
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 第二次解析:真正解碼出 Bitmap
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
採樣率的計算邏輯:
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// 取兩個方向比例的較小值,保證結果尺寸兩邊都不小於目標
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
把 getView 換成這樣:
imageView.setImageBitmap(
decodeSampleBitmapFromResource(getResources(), R.drawable.girl, 100, 100));
效果立竿見影:

滑得順了,但快速來回滑動一陣之後——崩了。

日誌裡是明確的 OOM:


仔細想一下問題出在哪:單張圖是變小了,但快速滑動意味著圖片在被瘋狂加載與釋放,某一瞬間同時存活於內存的 Bitmap 數量仍然會堆到失控。
的解法方向也就清楚了——讓滑出屏幕的圖片不要立刻離開,而是緩存起來重複使用。這正是 LruCache 的用武之地。
LruCache 的「最近最少使用」淘汰策略非常契合列表場景:滑走的項最近不會被用到,內存吃緊時優先丟棄它們。
/**
* 初始化內存緩存
*/
private void initLruCache() {
// 獲取可用內存上限,超出這個值就會 OOM
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// 用最大可用內存的 1/8 作為緩存容量
int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// 以 KB 為單位衡量每張圖片的實際佔用,默認只按張數計算
return bitmap.getByteCount() / 1024;
}
};
}
getView 中改成「先查緩存,命中就用,未命中再解碼並回填」:
String imageKey = String.valueOf(R.drawable.girl);
Bitmap bitmap = mMemoryCache.get(imageKey);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Bitmap bitmap2 = decodeSampleBitmapFromResource(
getResources(), R.drawable.girl, 100, 100);
imageView.setImageBitmap(bitmap2);
mMemoryCache.put(imageKey, bitmap2);
}
完整代碼:
public class MainActivity extends AppCompatActivity {
private LruCache<String, Bitmap> mMemoryCache;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initLruCache();
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new MyAdapter());
}
private void initLruCache() {
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount() / 1024;
}
};
}
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return 50;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = View.inflate(MainActivity.this, R.layout.list_item, null);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
String imageKey = String.valueOf(R.drawable.girl);
Bitmap bitmap = mMemoryCache.get(imageKey);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Bitmap bitmap2 = decodeSampleBitmapFromResource(
getResources(), R.drawable.girl, 100, 100);
imageView.setImageBitmap(bitmap2);
mMemoryCache.put(imageKey, bitmap2);
}
return view;
}
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampleBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
}
再跑一次,快速來回滑動也穩穩的:

最後一點補充:上面這個例子用單張固定圖片做演示,所以 imageKey 直接用資源 id。真實項目中 key 通常會是圖片 URL,同時還需要考慮 convertView 的復用、異步加載時的圖片錯位問題,以及磁盤緩存。如果不想自己折騰這些細節,直接上 Glide、Fresco、Picasso 這類成熟框架會輕鬆很多。

用百度手機助手連 Chinanet 免費無線上網,不用帳密
百度手機助手已與中國電信達成深度合作,在全國範圍內推出免費 WiFi 服務。只要所在位置有中國電信的 Chinanet 熱點,百度手機助手的使用者就能直接連上,不需要 C
Mac OS X 下 Eclipse Android 開發環境配置指南
本文整理在 Mac OS X 環境中,使用 Eclipse 與 ADT 建置 Android 開發環境的流程,適合需要快速回顧或重新配置的開發者。下載 ADT先到 And
Android 對話框系列(二):ProgressDialog 進度對話框
先看 main.xml,這裡放三顆按鈕,分別示範兩種進度對話框與自定義對話框。 自定義對話框的版面 custom_dialog.xml: 自定
Android 必知必會:動態切換著色模式與全螢幕模式(相容 4.4+)
若行動端閱讀不佳,歡迎改用 ==> Github 版。 本文示範如何透過程式碼動態切換頁面的著色模式與全螢幕模式(沉浸模式),並相容 Android 4.4 以上版