I’ve searched Google and this website many times, but can not find a solution to my question.
First, I understand, you can load images using something like:
int image = R.drawable.icon; (assuming there's a file called 'icon.png')
and I’ve read about, and tried using:
getResources().getIdentifier("resname", "restype", com.example.whatever);
But, here’s what I’m unable to do:
I want to be able to have pictures in the /res/drawable folder (I believe that’s the correct folder), WITHOUT KNOWING ANY OF THE NAMES OF THE FILES, and load them dynamically – at run-time.
One (of the many) things I’ve tried is (something like):
int[] images = new int[numberOfImages];
for( 0 to numberOfImages )
{
images[i] =
getResources().getIdentifier("resname", "restype", com.example.whatever);
}
This returns 0 EVERY TIME, so it’s not going to work
I’d like to get the name and integer identifier for every picture in the /res/drawables folder. Can this be done WITHOUT KNOWING ANY FILE NAMES?
———————————————————————-
[adding this after the question was resolved to help anyone that may run into the same issue in the future. It just shows that it does in fact work.]
Class resources = R.drawable.class;
Field[] fields = resources.getFields();
String[] imageName = new String[fields.length];
int index = 0;
for( Field field : fields )
{
imageName[index] = field.getName();
index++;
}
int result =
getResources().getIdentifier(imageName[10], "drawable", "com.example.name");
Well, if you have to do it, use reflection 🙂
Class resources = R.drawable.class; Field[] fields = resources.getFields(); for (Field field : fields) { System.out.println(field.getName()); }However, in a way, you are still hard-coding stuff, since you will only be putting a fixed set of drawables in your app. 🙂