In android you can access a resource with syntax like R..
what I want to do is to reach a set of images has naming convention.
for example I have 4 files in
well, if you know the suffix of the images, you can request the identifier for a drawable by getResources().getIdentifier(...) and then using the identifier get the drawable. So if you know how many images you have, then you can create a loop and store each of the drawables in a list. Just take into account that such a lookup is relatively expensive.
I don't believe you can trust the resource compiler to give your images sequential integer values. In the past I've always created a static array to store these.
private static int[] imgs = { R.id.draw_1, R.id.draw_2, R.id.draw_3, R.id.draw_4 };
With this you can then have a section of code like:
int curSlide = 0;
view.setBackgroundResource(imgs[curSlide]);
Although it is an old question, I just had a similar problem recently. I liked solution of jeffd, but storing a list of images ids in code is not the best idea. So, I created an xml file with the list, which I put in res/xml directory.
<?xml version="1.0" encoding="utf-8"?>
<list>
<image id="@drawable/draw_1"/>
<image id="@drawable/draw_2"/>
<image id="@drawable/draw_3"/>
<image id="@drawable/draw_4"/>
</list>
Images are stored in drawable
directory and are named draw_1.jpg
, draw_2.jpg
, etc.
Using this sort of xml has an advantage that availability of resources is checked at compile time, so if you have a typo, it won't compile.
Retrieving the list in code is simply parsing the xml, yet it's a bit verbose. XmlPullParser
has method getAttributeResourceValue
that allows getting resource id without dealing with any strings.
List<Integer> list = new ArrayList<>();
try {
while (parser.next() != XmlPullParser.END_DOCUMENT) {
if (parser.getEventType() == XmlPullParser.START_TAG &&
parser.getName().equals("image")) {
int imageId = -1;
for (int i = 0; i < parser.getAttributeCount(); ++i) {
if (parser.getAttributeName(i).equals("id")) {
list.add(parser.getAttributeResourceValue(i, -1));
}
}
}
}
}
catch (XmlPullParserException | IOException e) {
e.printStackTrace();
}
Another simpler solution would be using arrays as resources. I haven't tried this out, but you can see an example here: http://www.geeks.gallery/how-to-list-images-from-array-xml-in-android/ This is how to structure your xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="list">
<item>@drawable/draw_1</item>
<item>@drawable/draw_2</item>
<item>@drawable/draw_3</item>
</array>
</resources>
To access the array you can use this code:
TypedArray list = getResources().obtainTypedArray(R.array.list);
for (int i = 0; i < list.length(); ++i) {
int id = list.getResourceId(i, -1);
}
You Should identify all the Image as a Drawable .. and then you can use them as you can !