有许多图像,绘制foder所以不是手动创建的所有图像资源ID的数组,我要动态绘制文件夹中得到阵列中的所有图像。 目前I M采用这种code:
there are many images in drawable foder so instead manually creating array of all image resource ids , i want to get all images dynamically of drawable folder in array. currently i m using this code:
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++;
}
但在codeI需要手动编辑图像名称获取资源ID,但我想所有的图像与任何名称。
but in that code i need to manually edit the image name to get the resource id but i want to get all image with any name..
您可以使用反射
来实现这一目标。
you can Use Reflection
to achieve this.
导入字段
类
进口java.lang.reflect.Field中;
,然后在code写这个
and then write this in your code
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 []
现在持有在应用程序中引用的所有可绘制。
resArray[]
now holds references to all the drawables in your application.