Android Load images from drawable
In my android project I have several images int the drawable folder with a prefix that I would like to load in a HashMap :
开发者_Go百科Example :
PREFIX_G6.png
PREFIX_P7.png
PREFIX_P9.png
I can construct the bitmap for a specific Image Like this :
String drawableName = "PREFIX_" + "G6"; // ignore the extension
int drawableId = context.getResources().getIdentifier(drawableName, "drawable", PACKAGE_NAME);
Bitmap icon = BitmapFactory.decodeResource(context.getResources(), drawableId);
mIcons.put(drawableName, icon); // my Hashmap
In order to load all the images from the drawable folder I need to be able to list them and test if they start with my PREFIX_ any ideas ?
It is going to be quite a bit slower if this happens dynamically rather than with hard-coded values.
Nevertheless, you can try to use java reflection over your R class (warning: untested)
Class cls = R.drawable.class;
Field fieldlist[] = cls.getDeclaredFields();
for (Field fld : fieldlist) {
String fieldName = fld.getName();
if (fieldName.startsWith("PREFIX_") {
int drawableId = fld.getInt(null);
// do whatever with the drawable
}
}
精彩评论