我正在编写一个应用程序,其中使用放置在可绘制文件夹中的 200 多个图像,并且所有这些文件都遵循相同的命名约定,例如
thumb+X
要读取/显示这些文件,一种方法是按照以下步骤选择每个可绘制文件。
有什么方法可以使用循环或其他方式读取这些文件名..所以无论它将在drawable中更新多少文件,都不需要触摸源文件。
有什么建议吗!
R.drawable.XXX
假设您位于
int resource_id=getResources().getIdentifier("thumb"+x, "drawable", getPackageName());
中(getResources / getPackageName 是
Activity
方法)然后如果您需要
Activity
Drawable
请注意,通过名称访问可绘制对象会比较慢,您不应该滥用此方法。
Drawable myDrawable=getResources().getDrawable (resource_id);
现在循环播放
String name= "R.drawable.thumb";
完成了。
另一种方法是
for(int i=1;i<=200;i++){
String resource = name + i;
try {
Class c = Drawable.class;
Field idField = c.getDeclaredField(resource);
int resourceDrwable = idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
}
}