Android,引用R.drawable中的东西.使用变量?

Zug*_*dud 12 android android-resources

说我想R.drawable.*根据字符串的值动态加载图像文件

有没有办法做到这一点?好像我需要静态地引用任何内容R.

new*_*bie 18

您是否在XML文件中声明了图像的ID?如果您这样做,您可以使用以下方法:

假设你的res/drawable文件夹中有picture.png.

在您的活动中,您可以在main.xml文件中设置图像资源

<ImageView android:id="@+id/imageId" android:src="@drawable/picture"></ImageView>
Run Code Online (Sandbox Code Playgroud)

在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);
Run Code Online (Sandbox Code Playgroud)

imageString是动态名称.之后,您可以获取动态资源的标识符.

另一种方法,你可以这样做:

//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 );
Run Code Online (Sandbox Code Playgroud)

您将能够引用您的图像资源并将ImageView设置为它.


Yas*_*mar 9

int drawableId = getResources().getIdentifier(drawablename, "drawable", getPackageName());
imageview.setImageResource(drawableId);
Run Code Online (Sandbox Code Playgroud)

试试这个.这应该工作.