简体   繁体   English

如何以编程方式绘制特定的可绘制资源?

[英]How to draw specific drawable resource programmatically?

I have a set of images in my drawable resources. 我的可绘制资源中有一组图像。 Now I want to be able to change a placeholder image accordingly with image.setImageResource(R.id.name_of_image) programmatically. 现在,我希望能够以编程方式使用image.setImageResource(R.id.name_of_image)相应地更改占位符图像。

My ImageView is defined as ImageView image = findViewById(R.id.placeholder); 我的ImageView定义为ImageView image = findViewById(R.id.placeholder);

How would I do this? 我该怎么做? I have tried getIdentifier but that didn't work. 我已经尝试过getIdentifier但是没有用。

The images have the format Name.jpg 图像的格式为Name.jpg

EDIT: 编辑:

I currently have the following construction: 我目前有以下构造:

int resID = getResources().getIdentifier(name.toLowerCase(), "drawable", this.getPackageName());
ImageView image = findViewById(R.id.placeholder);
image.setImageResource(resID);

I have changed the image name to lowercase and it is now a png file. 我已将图片名称更改为小写,现在它是一个png文件。

Your images has to be in png format (prefered by android) and must contain only lowercase letters and digits ([a-z0-9_.]. Then you can use 您的图片必须为png格式(Android首选),并且必须仅包含小写字母和数字([a-z0-9_。]。然后您可以使用

image.setImageResource(R.drawable.name_of_image);

You can get the name of the drawable with this: 您可以通过以下方式获取可绘制的名称:

String name = context.getResources().getResourceEntryName(R.drawable.name_of_image);

To get the drawable with the string name: 要获取具有字符串名称的drawable:

int id = context.getResources().getIdentifier("name_of_image", "drawable", context.getPackageName());
image.setImageResource(id);

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

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