2014-02-13 33 views
0

我的資產文件夾中有一些圖像,我想通過使用SimpleAdapter將它們加載到ListView中。如何在資產文件夾中正確引用和映像?

我正在引用圖像的文件名,如:「my_image.jpg」。

下面是一些代碼:

ListView lv = (ListView) findViewById(R.id.list); 
rows = new ArrayList<Map<String, Object>>(); 
    for (String s : imageNames) { 
     rows.add(createRow(s)); 
    } 

SimpleAdapter adapter = new SimpleAdapter(
      this, 
      rows, 
      R.layout.card_list_row, 
      new String[] {"Image"}, 
      new int[] {R.id.list_row_image}); 
    lv.setAdapter(adapter); 

而且createRow方法:

private Map<String, Object> createCardRow(String s) { 
    Map<String, Object> row = new HashMap<String, Object>(); 
    row.put("Image", "file:///android_asset/" + s + ".jpg"); 
    return row; 
} 

當我執行,我得到了以下錯誤:

02-12 20:01:22.615: I/System.out(17876): resolveUri failed on bad bitmap uri: file:///android_asset/my_image.jpg 

而一個FileNotFoundException異常。我明顯知道該資源文件夾中存在該映像。我如何正確引用它?

回答

0

請使用AssetManager

使用硬編碼的絕對路徑從來都不是一個很好的做法,不管它的工作與否。

在網上有很多的源代碼示例,請谷歌爲它。

編輯:

你看到有在assetManager一個open方法返回指定的文件資源InputStream。然後,您可以使用decodeStream獲取Bitmap對象。

一旦你需要一個圖像,你可以使用上述步驟。正如你可以輕鬆找到一個例子,我不會在這裏展示它。

+0

我使用包含存儲在資產文件夾中的圖像文件名的數據庫。你認爲有更好的方法嗎? –

+0

數據庫擅長管理大量可能經常更改(添加/刪除)的對象或數據集。管理實施應該取決於你的要求。例如,如果您最多隻有十個圖像,則根本不需要使用「重」數據庫。 – suitianshi

+0

我有大約400個對象存儲在數據庫中,並且每個對象都有一個對圖像的引用。 –

0

你好嘗試使用下面的函數。

public void loadDataFromAsset(String imagenamefomdb) { 

     try { 



      InputStream ims = getAssets().open(imagenamefomdb); 
      Drawable d = Drawable.createFromStream(ims, "image"); 
      imageview.setImageDrawable(d); 
      ims.close(); 

     } catch (IOException ex) { 
      return; 
     } 

    } 

希望它爲你工作

相關問題