繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM