假设我想R.drawable.*
根据字符串的值动态加载图像文件
有没有办法做到这一点?似乎我需要静态引用R.
您是否在 XML 文件中声明了图像的 id?如果你这样做了,你可以使用以下方法:
假设您的 res/drawable 文件夹中有 picture.png。
在您的活动中,您可以在 main.xml 文件中设置您的图像资源
<ImageView android:id="@+id/imageId" android:src="@drawable/picture"></ImageView>
在第一个活动中
//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 是动态名称。之后,您可以获得动态资源的标识符。
另一种方法,你可以这样做:
//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 设置为它。
int drawableId = getResources().getIdentifier(drawablename, "drawable", getPackageName());
imageview.setImageResource(drawableId);
试试这个。这应该有效。
Class res = R.string.class;
Field field = res.getField("x" + pos);
headerId = field.getInt(null);
header.setText(headerId);
这也适用于可绘制对象,只需编辑字符串。标题部分不是必需的,它只是从我前一阵子写的东西中提取的一个例子。