简体   繁体   English

如何从变量设置图像视图资源?

[英]How to set imageview resource from variable?

I have a lot of images (hundreds) and I need to put some of them as a resource of ImageView , but if I would create If Then set Image to Image name, I die from these tons of code.我有很多图像(数百个),我需要将其中一些作为ImageView的资源,但是如果我创建 If Then 将 Image 设置为图像名称,我会死于这些大量的代码。 I want to set Image resource which name is inside a variable, but I can't find out how.我想设置名称在变量内的图像资源,但我不知道如何。 If I have img.setImageResource(R.drawable.my_image);如果我有img.setImageResource(R.drawable.my_image); How can I assign variable name at my_image instead of true image name?如何在my_image分配变量名称而不是真实图像名称? Please help.请帮忙。 Thanks.谢谢。

Try this:试试这个:

 String resourceName = "clouds";
 int resourceIdentifier = getResources().getIdentifier(resourceName, "drawable", Constants.CURRENT_CONTEXT.getPackageName());

Then然后

imgView.setImageResource(resourceIdentifier);

I don't know if I clearly understood your request but why don't you try to do that instead :我不知道我是否清楚地理解了您的要求,但您为什么不尝试这样做:

    int my_image = R.id.my_image;
    img.setImageResource(ContextCompat.getDrawable(this, my_image));

https://stackoverflow.com/a/29146895/8526518 for more informations about ContextCompat https://stackoverflow.com/a/29146895/8526518有关 ContextCompat 的更多信息

if you can prefer assets folder rather than resource, then you can try this code如果您更喜欢资产文件夹而不是资源,那么您可以尝试此代码

create sub-folder in assets directory.在资产目录中创建子文件夹。 use getAssets().list() for getting all file names from assets:使用 getAssets().list() 从资产中获取所有文件名:

String[] images =getAssets().list("images");
ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));

Now to set image in imageview you first need to get bitmap using image name from assets :现在要在 imageview 中设置图像,您首先需要使用 assets 中的图像名称获取位图:

InputStream inputstream=mContext.getAssets().open("images/"
                                      +listImages.get(position));
Drawable drawable = Drawable.createFromStream(inputstream, null);
imageView.setImageDrawable(drawable);

just a convenient refactoring of the S-Sh answer if you use kotlin and like using its extensions functions:如果您使用 kotlin 并喜欢使用其扩展功能,则只是对 S-Sh 答案的方便重构:

fun ImageView.loadDrawableFromName(name:String, ctx: Context, visible:Int=View.VISIBLE){
    val resId = ctx.resources.getIdentifier(name, "drawable", ctx.packageName)
    this.setImageResource(resId)
    this.visibility = visible
}

you can call it in both ways:您可以通过两种方式调用它:

imgname="IMGNAME"
myimageview.loadDrawableFromName(imgname, ctx)

and

imgname="IMGNAME"
myimageview.loadDrawableFromName("@drawable/$imgname", ctx)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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