本文實例講述了Android讀取assets目錄下的所有圖片并顯示的方法。分享給大家供大家參考。具體方法分析如下:
在assets文件夾里面的文件都是保持原始的文件格式,需要用AssetManager以字節流的形式讀取文件。
1. 先在Activity里面調用getAssets() 來獲取AssetManager引用。
2. 再用AssetManager的open(String fileName, int accessMode) 方法則指定讀取的文件以及訪問模式就能得到輸入流InputStream。
3. 然后就是用已經open file 的inputStream讀取文件,讀取完成后記得inputStream.close() 。
4.調用AssetManager.close() 關閉AssetManager。
需要注意的是,來自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) {
// TODO Auto-generated catch block
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);
// Assign the bitmap to an ImageView in this layout
} catch (IOException e) {
e.printStackTrace();
} finally {
if (open != null) {
try {
open.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
這樣所有的map中的關鍵字“iv"處理論上就保存了我們讀取的bitmap,可以結果并非如此,大家應該注意到了在”bg“關鍵字處我們也保存了一個圖片,只不過它是通過R.drawable.方式獲取的,實驗證明這種方式是可以成功讀取并顯示的。為什么從assets中讀取的bitmap不能顯示呢?解決辦法是:
實現 ViewBinder接口,對兩種的資源id和bitmap 情況進行說明:
adapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(
View view,
Object data,
String textRepresentation) {
// TODO Auto-generated method stub
if((view instanceof ImageView) && (data instanceof Bitmap)) {
ImageView imageView = (ImageView) view;
Bitmap bmp = (Bitmap) data;
imageView.setImageBitmap(bmp);
return true;
}
return false;
}
});
這樣就可以了。
還有一種情況是,我們在非Activity類中讀取assets文件下的內容,這個時候就得把調用者(Activity類)的context傳遞過去,然后在這個非Activity類中使用context.getAssets()方式調用就行了。舉個簡單例子:
我們有一個HomeActivity,然后我們它里面調用GetData.initdata(HomeActivity.this).
在GetData類的initdata方法肯定是這樣定義的:
public void initdata(Context context)
{
//other codes...
String[] list_image = null;
try {
//得到assets/processedimages/目錄下的所有文件的文件名,以便后面打開操作時使用
list_image = context.getAssets().list("processedimages");//attention this line
} catch (IOException e1)
{
e1.printStackTrace();
}
//other codes.....
}
因為getAssets方法是Context下的方法,在非Activity類中是不能直接使用的。
希望本文所述對大家的Android程序設計有所幫助。