+-

在drawable foder中有很多图像,所以相反手动创建所有图像资源ID的数组,我想动态获取数组中可绘制文件夹的所有图像.
目前我正在使用此代码:
目前我正在使用此代码:
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但我想获得任何名称的所有图像..
最佳答案
你可以使用Reflection实现这一目标.
导入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 []现在保存对应用程序中所有drawable的引用.
点击查看更多相关文章
转载注明原文:android – 动态获取数组中的所有图像资源ID - 乐贴网