how to select from resources randomly (R.drawable.xxxx)

chinmay dhodapkar picture chinmay dhodapkar · Aug 16, 2010 · Viewed 9.4k times · Source

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

Answer

rharter picture rharter · Jan 7, 2014

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!

  1. 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>
    
  2. 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();
    
  3. Profit!