![](/img/trans.png)
[英]How to set ImageView Resource from Java Image data type in Android
[英]How to set imageview resource from variable?
我有很多图像(数百个),我需要将其中一些作为ImageView
的资源,但是如果我创建 If Then 将 Image 设置为图像名称,我会死于这些大量的代码。 我想设置名称在变量内的图像资源,但我不知道如何。 如果我有img.setImageResource(R.drawable.my_image);
如何在my_image
分配变量名称而不是真实图像名称? 请帮忙。 谢谢。
试试这个:
String resourceName = "clouds";
int resourceIdentifier = getResources().getIdentifier(resourceName, "drawable", Constants.CURRENT_CONTEXT.getPackageName());
然后
imgView.setImageResource(resourceIdentifier);
我不知道我是否清楚地理解了您的要求,但您为什么不尝试这样做:
int my_image = R.id.my_image;
img.setImageResource(ContextCompat.getDrawable(this, my_image));
https://stackoverflow.com/a/29146895/8526518有关 ContextCompat 的更多信息
如果您更喜欢资产文件夹而不是资源,那么您可以尝试此代码
在资产目录中创建子文件夹。 使用 getAssets().list() 从资产中获取所有文件名:
String[] images =getAssets().list("images");
ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));
现在要在 imageview 中设置图像,您首先需要使用 assets 中的图像名称获取位图:
InputStream inputstream=mContext.getAssets().open("images/"
+listImages.get(position));
Drawable drawable = Drawable.createFromStream(inputstream, null);
imageView.setImageDrawable(drawable);
如果您使用 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
}
您可以通过两种方式调用它:
imgname="IMGNAME"
myimageview.loadDrawableFromName(imgname, ctx)
和
imgname="IMGNAME"
myimageview.loadDrawableFromName("@drawable/$imgname", ctx)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.