Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 讀取 assets 目錄下所有圖片並顯示的完整做法

編輯:關於 Android 程式設計

assets 目錄裡的檔案會以原始格式保存,不會被編譯成資源索引,因此不能像 R.drawable 那樣直接引用,必須透過 AssetManager 以串流的方式讀取。本文示範如何把 assets 底下某個子目錄的所有圖片列出、解碼,最後顯示在清單中。

讀取 assets 的四個基本步驟

1. 在 Activity 中呼叫 getAssets() 取得 AssetManager 實例。

2. 呼叫 AssetManager 的 open(String fileName, int accessMode),指定檔名與存取模式,取得 InputStream。

3. 用這個 InputStream 讀取內容,讀完務必呼叫 close(),否則檔案描述符會被佔用。

4. 最後呼叫 AssetManager.close() 釋放資源。

要特別注意:Resources 與 Assets 中的檔案都是唯讀的,無法寫入。

Activity 中的實作範例

List<Map<String, Object>> cateList = new ArrayList<Map<String, Object>>();
String[] list_image = null;
try {
    // 取得 assets/processedimages/ 底下所有檔名
    list_image = context.getAssets().list("processedimages");
} catch (IOException e1) {
    e1.printStackTrace();
}
for (int i = 0; i < list_image.length; ++i) {
    InputStream open = null;
    try {
        String temp = "processedimages/" + list_image[i];
        open = context.getAssets().open(temp);
        Bitmap bitmap = BitmapFactory.decodeStream(open);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", list_image[i]);
        map.put("iv", bitmap);
        map.put("bg", R.drawable.phone_vip_yes);
        map.put("cate_id", i);
        cateList.add(map);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (open != null) {
            try { open.close(); } catch (IOException e) { e.printStackTrace(); }
        }
    }
}

一個容易踩到的坑

上面的程式邏輯上把 Bitmap 放進了 map 的 "iv" 鍵,但實測卻顯示不出來;反觀用 R.drawable.xxx 取得的 "bg" 圖片卻能正常顯示。原因在於SimpleAdapter 預設只認得資源 id(int)與字串,它不會自動把 Bitmap 物件塞進 ImageView。

解法:實作 ViewBinder

透過 ViewBinder 告訴 Adapter 遇到 Bitmap 時該怎麼處理:

adapter.setViewBinder(new ViewBinder() {
    @Override
    public boolean setViewValue(View view, Object data, String textRepresentation) {
        if ((view instanceof ImageView) && (data instanceof Bitmap)) {
            ImageView imageView = (ImageView) view;
            Bitmap bmp = (Bitmap) data;
            imageView.setImageBitmap(bmp);
            return true;
        }
        return false;
    }
});

這樣兩種型別(資源 id 與 Bitmap)就能各自走對應的分支。

在非 Activity 類別中讀取 assets

getAssets() 是 Context 的方法,所以如果你把讀檔邏輯抽到一個工具類或資料類裡,就必須把 Activity 的 Context 傳進去。例如 HomeActivity 中這樣呼叫:

GetData.initdata(HomeActivity.this);

而 GetData 的方法簽名則定義為:

public void initdata(Context context) {
    String[] list_image = null;
    try {
        list_image = context.getAssets().list("processedimages"); // 注意這裡用的是傳入的 context
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    // other codes...
}

順帶一提,若要讀取大量圖片,建議改用自訂 BaseAdapter 並搭配 convertView 複用,避免一次性把所有 Bitmap 都載入記憶體而觸發 OutOfMemoryError。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved