Android, reference things in R.drawable. using variables?

ⅰ亾dé卋堺 提交于 2019-11-28 12:02:51
newbie

Have you declared the id for the image in XML file? If you did, you can use the following method:

Let's say you have picture.png in your res/drawable folder.

In your activity, you can set your image resource in the main.xml file

<ImageView android:id="@+id/imageId" android:src="@drawable/picture"></ImageView>

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 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 );

You will be able to reference your image resource and set your ImageView to it.

Yashwanth Kumar
int drawableId = getResources().getIdentifier(drawablename, "drawable", getPackageName());
imageview.setImageResource(drawableId);

Try this. This should work.

user1015747
Class res = R.string.class;
Field field = res.getField("x" + pos);
headerId = field.getInt(null);
header.setText(headerId);

this works with drawables as well, just edit the string. the header part is not required, it's just an example pulled from something I wrote a while ago.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!