[英]How to draw specific drawable resource programmatically?
我的可绘制资源中有一组图像。 现在,我希望能够以编程方式使用image.setImageResource(R.id.name_of_image)
相应地更改占位符图像。
我的ImageView定义为ImageView image = findViewById(R.id.placeholder);
我该怎么做? 我已经尝试过getIdentifier
但是没有用。
图像的格式为Name.jpg
编辑:
我目前有以下构造:
int resID = getResources().getIdentifier(name.toLowerCase(), "drawable", this.getPackageName());
ImageView image = findViewById(R.id.placeholder);
image.setImageResource(resID);
我已将图片名称更改为小写,现在它是一个png文件。
您的图片必须为png格式(Android首选),并且必须仅包含小写字母和数字([a-z0-9_。]。然后您可以使用
image.setImageResource(R.drawable.name_of_image);
您可以通过以下方式获取可绘制的名称:
String name = context.getResources().getResourceEntryName(R.drawable.name_of_image);
要获取具有字符串名称的drawable:
int id = context.getResources().getIdentifier("name_of_image", "drawable", context.getPackageName());
image.setImageResource(id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.