如何更换R.drawable"。someString"drawable、QUOT、someString

2023-09-06 13:50:41 作者:青春为你更新

我有我的项目的一些图片。图像的名称存储在一个字符串,我想setImageResource(R.drawable.....。);与图像的名字,但问题的字符串,这是行不通的。

I have some Images in my project. The name of the image is stored in a String and I would like to setImageResource(R.drawable."....."); with the string of the image name but the problem is that this is not working.

我怎样才能做到这一点?

How can I do this?

推荐答案

这是不是一个正确的语法,你必须得到编译时错误,改变图像资源之前,你必须知道,所有的资源提供了一个ID,这些ID是存储到R.java文件。 ID存储成整数格式,并在你的应用程序,您可以通过这些标识获取所有这些资源,叫不上名字,所以你需要获取资源的ID首先,通过:

this is not a right syntax, and you must getting compiler time error, before altering image resource you must know that, all resources provided an id, these ids are stored into R.java file. Ids are stored into integer format, and in your application you can fetch all these resources by these id, not by name, so you need to fetch id of resource at first, by:

String mDrawableName = "myimg";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

然后用这个渣油。

and then use this resID.