Android的,在R.drawable参考的东西。使用变量? [英] Android, reference things in R.drawable. using variables?
问题描述
Greetigns,说我要在R.drawable基于字符串的值动态一些图像文件。有没有办法做到这一点?好像我需要静态是指在研发什么。
Greetigns, say I want to dynamically some image file in R.drawable based on the value of a string. Is there a way to do this? Seems like I need to statically refer to anything in R.
推荐答案
你声明的ID为XML文件中的形象呢?如果你做到了,你可以用下面的方法:
Have you declared the id for the image in XML file? If you did, you can use the following method:
假设你已经picture.png在RES /绘制文件夹。
Let's say you have picture.png in your res/drawable folder.
在你的活动,你可以设置你的图像资源在main.xml中的文件
In your activity, you can set your image resource in the main.xml file
<ImageView android:id="@+id/imageId" android:src="@drawable/picture"></ImageView>
在FirstActivity
In FirstActivity
//to retrieve image using id set in xml.
String imageString = "imageId"
int resID = getResources().getIdentifier(imageString , "id", "package.name");
ImageView image = (ImageView) findViewById(resID);
和imagestring是动态的名称。之后就可以得到动态资源的标识符。
imageString is the dynamic name. After which you can get the identifier of the dynamic resource.
另一种方法,你可以这样做:
Another method, you can do this:
//to retrieve image in res/drawable and set image in ImageView
String imageName = "picture"
int resID = getResources().getIdentifier(imageName, "drawable", "package.name");
ImageView image;
image.setImageResource(resID );
您将能够引用您的图像资源和设置您的ImageView的吧。
You will be able to reference your image resource and set your ImageView to it.
这篇关于Android的,在R.drawable参考的东西。使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!