[英]How to get specific images Resource from Assets Folder?
我在資產文件夾下有8個不同的植物物種圖像,我在數據庫的資產目錄中緩存了8個圖像資產文件名(對應於路徑,例如foxtail.png,orchid.png)。 (加上其他信息)
我正在RecyclerView中顯示這8家工廠。 單擊任何工廠將打開“詳細信息活動”。 (傳遞保存在資產文件夾Eg foxtail.png中的圖像文件名)
如何在Assets文件夾中選擇與傳遞給Detail Activity的文件名匹配的特定圖像文件,並將其設置為ImageView?
您可以:
以流形式打開文件
InputStream imageStream = null;
try {
// get input stream
imageStream = getAssets().open("foxtail.png");
// load image as Drawable
Drawable drawable= Drawable.createFromStream(imageStream, null);
// set image to ImageView
image.setImageDrawable(drawable);
}
catch(IOException ex) {
return;
}
最后記得用關閉流
if(imageStream !=null){
imageStream.close();
}
要么
將圖像移動到res / drawable文件夾中 ,可以使用以下方式加載圖像:
String yourImageName = getImageNameFromDB();
int resId= getResources().getIdentifier(yourImageName, "drawable", "com.example.yourpackegename.");
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(resId);
要么
像這樣 (總是將圖像放入res / drawable中):
private enum Plant {
foxtail, orchid, xyz;
}
String value = getPlantFromDB();
Plant plant = Plant.valueOf(value); // surround with try/catch
switch(plant) {
case foxtail :
resId= R.drawable.foxtail
break;
case orchid :
resId= R.drawable.orchid
break;
default :
resId= R.drawable.xyz
break;
Drawable drawable = getResources().getDrawable(resId);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(drawable);
使用Resource Drawable Id在每個ImageView / View上設置標簽。 R.drawable.foxtail
例如。 imageView.setTag(R.drawable.foxtail)
或view.setTag(R.drawable.foxtail)
選擇一個后,獲取標簽並將其發送到下一個活動:
然后再次檢查。
imageTag = getIntent().getIntExtra("chosenPlant");
if ( imageTag == R.drawable.foxtail ){
//Perform action if this pic was selected (foxtail.png)
newImageView.setImageResource(R.drawable.foxtail);
} else ...
您可以創建一個包含資源ID的int數組。
int images[]={
R.drawable.image_1,
R.drawable.image_2,
R.drawable.image_3,
R.drawable.image_4,
R.drawable.image_5,
R.drawable.image_6,
R.drawable.image_7,
R.drawable.image_8
};
在數據庫中,存儲與資源數組中圖像位置相對應的圖像ID。
| id | image_id | information |
-------------------------------
| 0 | 2 | info_0 |
| 1 | 0 | info_1 |
| 2 | 4 | info_2 |
因此,當您從數據庫中獲取行時,可以使用image_id從數組中檢索相應的圖像
ImageView imageView = (ImageView)v.findViewById(R.id.imageView);
imageView.setImageResource(images[image_id]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.