简体   繁体   English

使用字符串访问Android可绘制资源

[英]Accessing Android drawable resource with a string

I apologize if this seems really simple but I can't figure it out. 如果这看起来真的很简单,我深表歉意,但我无法弄清楚。 I have an ImageButton that I want to change the image of at run-time based on a button click. 我有一个ImageButton,我想在运行时基于按钮单击来更改其图像。 I have 5 images in my res folder. 我的res文件夹中有5张图像。 When the user hits the "Next" button, I want it to go to the next image. 当用户单击“下一步”按钮时,我希望它转到下一张图像。 The file names of the images are image1.png, image2.png, etc. 图像的文件名是image1.png,image2.png等。

I know I you can change the image by doing: 我知道我可以通过以下方式更改图像:

imgButton.setImageResource(R.drawable.image2);

I have a counter (int) to keep track of the image number being displayed. 我有一个计数器(int)来跟踪显示的图像编号。 But how would i change the image to the next image? 但是如何将图像更改为下一个图像? Any help would be appreciated. 任何帮助,将不胜感激。

Create an Array of integers to hold the references to your images, eg 创建一个整数数组来保存对图像的引用,例如

int[] images = new int[5];
images[0] = R.drawable.image001;
images[1] = R.drawable.image002;
images[2] = R.drawable.image003;
images[3] = R.drawable.image004;
images[4] = R.drawable.image005;

And then increment your counter on each click, and set the image resource using a value from your array: 然后在每次点击时增加计数器,并使用数组中的值设置图像资源:

imgButton.setImageResource(images[counter]);

Easy when you know how... ;) 当您知道如何时就很容易...;)

You can use reflection to get the id of an image based on a string filename. 您可以使用反射来基于字符串文件名获取图像的ID。

Field f = R.getClass().getField("image2");
int id = f.getInt(null); // use null for static fields
imgButton.setImageResource(id);

Edit: Or as this other question mentioned, you can ask Resources for the id using getIdentifier() . 编辑:或者正如提到的另一个问题 ,您可以使用getIdentifier()向资源询问ID。 This is slower than getting by static const, but might work for you. 这比通过静态const慢,但可能对您有用。

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

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