如何从资产文件夹中获取特定图像资源?

Joh*_*ith 1 java resources android assets imageview

我在assets文件夹下有8个不同的植物物种图像,我在数据库的assets目录中缓存了8个图像资产文件名(对应于路径,例如foxtail.png,orchid.png)。(加上其他信息)

我正在“在 RecyclerView 中显示 8 种植物”。单击任何植物会打开详细信息活动。(传递保存在资产文件夹中的图像文件名,例如 foxtail.png)

如何在资产文件夹中选择与传递给 Detail Activity 的文件名匹配的特定图像文件并将其设置为 ImageView?

Nic*_*nze 5

你可以:

将文件作为流打开

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;
}
Run Code Online (Sandbox Code Playgroud)

最后记得关闭流

if(imageStream !=null){
    imageStream.close();
}
Run Code Online (Sandbox Code Playgroud)

或者

在 res/drawable 文件夹中移动您的图像,您可以使用以下命令加载图像:

String yourImageName = getImageNameFromDB();
int resId= getResources().getIdentifier(yourImageName, "drawable", "com.example.yourpackegename.");
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(resId);
Run Code Online (Sandbox Code Playgroud)

或者

这样的事情(总是与图像转换成RES /绘制):

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);
Run Code Online (Sandbox Code Playgroud)