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 r
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.
- @drawable/bg_loading_1
- @drawable/bg_loading_2
- @drawable/bg_loading_3
- @drawable/bg_loading_5
- @drawable/bg_loading_6
- @drawable/bg_loading_7
- @drawable/bg_loading_8
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!