I want to display a random image from the bunch of images i have stored in res/drawable.
The only technique that I know is to access a particular image if you know its resource id. Is there a way to access the images by using the filenames or something else (which can be constructed at runtime)?
I want to randomly select an image at runtime. Any suggestions/ideas appreciated :)
Thanks Chinmay
I realize this is a super old question, but wanted to provide a good solution for any Googlers.
Access resources by name is much less efficient than by id. The whole point of the resource system is so that you don't have to resolve names, and can use ids instead.
What you need to do is utilize the Array Resource type. Follow along with my easy steps! I make random images...Fun!
Create an array resource that includes all of the images you want to choose from. I put this in my res/values/arrays.xml
file but it can really go anywhere.
<array name="loading_images">
<item>@drawable/bg_loading_1</item>
<item>@drawable/bg_loading_2</item>
<item>@drawable/bg_loading_3</item>
<item>@drawable/bg_loading_5</item>
<item>@drawable/bg_loading_6</item>
<item>@drawable/bg_loading_7</item>
<item>@drawable/bg_loading_8</item>
</array>
Next, get the TypedArray
from the Resources
and use that to choose a random image.
TypedArray images = getResources().obtainTypedArray(R.array.loading_images);
int choice = (int) (Math.random() * images.length());
mImageView.setImageResource(images.getResourceId(choice, R.drawable.bg_loading_1));
images.recycle();
Profit!
You can also access resources by name, which may be a viable approach to solving your problem if you know the names of the resources or can derive them according to some pre-defined naming scheme.
You have to map the name to the identifier using the getIdentifier method of the Resources
class.
String name = "resource" + rng.nextInt(count);
int resource = getResources().getIdentifier(name, "drawable", "com.package");
The documentation for this method says:
Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
This is true but need not be a problem if you are doing it in code that isn't performance sensitive.
Alternatively, if you don't mind listing the resources in XML, you could create a typed array that you can then randomly select from.
The items in res/drawable are enumerated in the R.drawable class at compile time. You could probably use reflection to get a list of the members of that class, and then select from that list randomly.
I can't think of anything you can do at runtime. You could possibly create an array of address integers (since the R.drawable.xxxx
is essentially an integer address) and then use java.util.Random
to select a random resource address from your array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With