編輯:關於 Android 程式設計
在 Android 中載入大量圖片時,最令人頭痛的就是記憶體溢出(OOM)問題。本文整理了一套完整的做法,從圖片資源的組織、螢幕尺寸計算,到異步載入與縮放,一步步教你如何安全地把圖片顯示到 GridView 上。
先以陣列的形式管理要顯示的圖片資源 ID,並建立一個集合用來保存載入後的 Bitmap:
private int fore[];
private int back[];
fore = new int[]{R.drawable.a0, R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4,
R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8, R.drawable.a9,
R.drawable.a910, R.drawable.a911, R.drawable.a912, R.drawable.a913, R.drawable.a914};
back = new int[]{R.drawable.b0, R.drawable.b1, R.drawable.b2, R.drawable.b3, R.drawable.b4,
R.drawable.b5, R.drawable.b6, R.drawable.b7, R.drawable.b8, R.drawable.b9,
R.drawable.b910, R.drawable.b911, R.drawable.b912, R.drawable.b913, R.drawable.b914};
// 用來保存載入的圖片
private List<Bitmap> bitmapResource = new ArrayList<Bitmap>();
GridView grid; // 類似九宮格的圖片顯示控制項
Handler handler; // 用來傳遞訊息的 Handler
取得螢幕寬度後,透過 AsyncTask 在背景執行緒中完成耗時的圖片縮放,避免阻塞 UI 主執行緒:
int width = (int) (getWindowManager().getDefaultDisplay().getWidth() / density);// 取得螢幕寬度
ImageResource ir = new ImageResource();
// 使用 getPicture() 方法載入圖片
public void getPicture() {
new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... params) {
// 背景執行,耗時操作都放在這裡
publishProgress(); // 更新任務進度
loadingBitmap(getResources(), width, 3);// 縮放圖片,3 為顯示列數
return null;
}
@Override
protected void onPostExecute(Object result) {
// doInBackground 完成後,此方法會在 UI 執行緒被呼叫
handler.removeCallbacks(update);
message.setVisibility(View.GONE);
author_message.setVisibility(View.GONE);
grid.setVisibility(View.VISIBLE);
grid.setNumColumns(3); // 設定列數
grid.setHorizontalSpacing(20); // 欄間距
grid.setVerticalSpacing(40); // 列間距
grid.setAdapter(adapter);
grid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent intent = new Intent();
intent.setClass(MenuActivity.this, ShowActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("num", position); // 傳遞位置值
intent.putExtras(bundle);
MenuActivity.this.startActivity(intent);
}
});
adapter.notifyDataSetChanged(); // 通知 UI 依新資料重繪
super.onPostExecute(result);
}
protected void onProgressUpdate(Object... values) {
handler = new Handler();
handler.post(update); // 依執行緒更新進度
super.onProgressUpdate(values);
}
}.execute();
}
真正防止記憶體溢出的核心,在於 BitmapFactory.Options 的 inJustDecodeBounds 與 inSampleSize 兩個屬性:
public void loadingBitmap(Resources resources, int width, int num) {
BitmapFactory.Options opts = new BitmapFactory.Options();
// 僅回傳圖片的寬高,不實際載入,因此幾乎不佔記憶體,能大幅降低 OOM 發生率
opts.inJustDecodeBounds = true; // 設為 true 時不返回實際 bitmap,只取得解碼邊界資訊
Bitmap temp = BitmapFactory.decodeResource(resources, fore[0], opts);
// 向上取整計算縮放比例
int radio = (int) Math.ceil(opts.outWidth / (width * 1.0 / num - 30));
// Math.ceil(12.2) → 13;Math.ceil(12.7) → 13;Math.ceil(12.0) → 12
opts.inSampleSize = radio; // 縮略圖為原圖的幾分之一
if (null != temp) {
temp.recycle(); // 回收
}
opts.inJustDecodeBounds = false; // 設為 false 才能依縮放比例載入想要的圖片
for (int i = 0; i < fore.length; i++) {
Bitmap bitmap = BitmapFactory.decodeResource(resources, fore[i], opts);
bitmapResource.add(bitmap); // 逐一加入集合
}
}
BaseAdapter adapter = new BaseAdapter() {
public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv = new ImageView(MenuActivity.this);
iv.setMaxWidth(width / 3 - 30); // 設定寬度
iv.setAdjustViewBounds(true); // 保持寬高比
iv.setImageBitmap(ir.getIconBitmap(position));
return iv;
}
@Override public long getItemId(int position) { return position; }
@Override public Object getItem(int arg0) { return arg0; }
@Override public int getCount() { return ir.size(); }
};
最後,透過 Handler 搭配 postDelayed 實作一個輕量的進度更新機制,當進度達到 100% 時停止輪詢:
Runnable update = new Runnable() {
@Override
public void run() {
int progress = ir.getProgress();
if (null != message) {
message.setText("數據加載中(" + progress + "%),請稍等……\n\n");
}
if (100 == progress) {
handler.removeCallbacks(update); // 載入完成,停止定時器
} else {
handler.postDelayed(update, 200); // 每 0.2 秒更新一次
}
}
};
Android 開發實例:搜尋 SD 卡中的檔案
需求背景 在 Android 應用中,經常需要瀏覽或搜尋外部儲存空間的檔案。當檔案數量龐大時,若能提供關鍵字搜尋,使用者就能更快找到目標。本文以一個簡單範例說明如何建立搜
Android SQLite 資料庫實作指南:建立、操作與 Cursor 讀取
SQLite 是 Android 常用的輕量級嵌入式關聯式資料庫。它不需要獨立伺服器,適合儲存在應用程式私有空間中的結構化資料。 資料庫位置 在 Android 中,SQ
Android 實戰:為 APK 程序簽名與重新簽名的方法
簽名是 Android 應用分發與系統校驗的重要環節。本文將詳細介紹如何使用 signapk 工具為 APK 簽名,以及如何透過命令行為 APK 重新簽名。 一、簽名工具
Android 捕獲與攔截 Home 鍵的示例代碼
默認情況下,按下 Home 鍵會讓應用回到桌面。但在某些特殊場景(例如自助終端、專用設備)中,我們可能希望攔截 Home 鍵、停留在當前界面。從 API Level 5