drawable foder 中有很多图像,因此我想手动创建所有图像资源 id 的数组,而是动态获取数组中 drawable 文件夹的所有图像。 目前我正在使用这段代码:
for(int i=1;i<=9;i++)
{
int imageKey = getResources().getIdentifier("img"+i, "drawable", getPackageName());
ImageView image = new ImageView(this);
image.setId(imgId);
image.setImageResource(imageKey);
image.setScaleType(ImageView.ScaleType.FIT_XY);
viewFlipper.addView(image, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
imgId++;
}
但在该代码中我需要手动编辑图像名称以获取资源 ID 但我想获取任何名称的所有图像..
最佳答案
您可以使用反射
来实现这一点。
导入Field
类
import java.lang.reflect.Field;
然后在你的代码中写这个
Field[] ID_Fields = R.drawable.class.getFields();
int[] resArray = new int[ID_Fields.length];
for(int i = 0; i < ID_Fields.length; i++) {
try {
resArray[i] = ID_Fields[i].getInt(null);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resArray[]
现在包含对应用程序中所有可绘制对象的引用。
关于android - 动态获取数组中的所有图像资源ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12274891/