Assets 目錄適合存放應用打包時固定的資源檔(如預設圖片、設定檔、字型)。讀取方式需透過 AssetManager.open() 取得 InputStream,再經 BitmapFactory.decodeStream() 解碼為 Bitmap。注意資源路徑區分大小寫,且不支援子目錄遞迴列舉。
public Bitmap loadBitmapFromAssets(Context context, String fileName) {
InputStream is = null;
try {
// 路徑相對於 assets 根目錄,如 "images/logo.png"
is = context.getAssets().open(fileName);
return BitmapFactory.decodeStream(is);
} catch (IOException e) {
Log.e("Assets", "Load bitmap failed: " + fileName, e);
return null;
} finally {
if (is != null) {
try { is.close(); } catch (IOException ignored) {}
}
}
}
// 佈局檔
<ImageView
android:id="@+id/ivLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
// Activity/Fragment
ImageView ivLogo = findViewById(R.id.ivLogo);
Bitmap bitmap = loadBitmapFromAssets(this, "brand/logo.png");
if (bitmap != null) {
ivLogo.setImageBitmap(bitmap);
}
BitmapFactory.Options.inSampleSize 降低記憶體佔用,避免 OOM。
| 現象 | 可能原因 | 解決 |
|---|---|---|
| FileNotFoundException | 路徑大小寫錯誤、檔案未打包進 APK | 確認 assets 目錄結構、Build 輸出 APK 解壓檢查 |
| decodeStream 回傳 null | 檔案損壞、格式不支援、流已關閉 | 驗證檔案完整性、確保流在 decode 前未關閉 |
| ANR | 主執行緒解碼大圖 | 移至背景執行緒、加入 inSampleSize |
善用 Assets 機制,能讓應用離線也能呈現豐富視覺資源,且不佔用內部儲存空間。