Petar Mijović
Petar Mijović

Reputation: 347

picking random image from resources

Hi I am working on simple android app. App is contained of only image view. On image view click picture that is shown should be changed. My question is how can i get the list of resources or resource image by index. For example in drawable I have 100 images name from s1 - s100. And i want to display one of them using random function like this:

private void ImageView_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            int index = r.Next() % 100;

            //code where I get picture on "index place" from my drawable folder.
        }

Thanks!

Upvotes: 3

Views: 1955

Answers (4)

Petar Mijović
Petar Mijović

Reputation: 347

This is the most elegant solution, @Budius gave it in Java, this is C#:

private void ImageView_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            int index = r.Next() % 36;
            String name = "s" + index;
            int drawableId = Resources.GetIdentifier(
                                name,               // the name of the resource
                                "drawable",         // type of resource
                                "Us.Us"); // your app package name
            imageView.SetImageResource(drawableId);

        }

"Us.Us" is my package name.

Upvotes: 0

Budius
Budius

Reputation: 39846

I see you already have accepted answer, but it's a very boring way to achieve what u want because it needs the developer to write the array with all hundreds of items. A much simpler way of achieving it is to getting the identifier for the drawable directly.

I'm not sure on Xamarin/C# how that would be, but on Java you use like this:

Random r = new Random();
int index = r.nextInt(100);
String name = "s" + index;
int drawableId = getResources().getIdentifier(
                    name,               // the name of the resource
                    "drawable",         // type of resource
                    getPackageName())); // your app package name
imageView.setImageResource(drawableId);

Upvotes: 2

Suresh Kumar
Suresh Kumar

Reputation: 2034

Create any arrays.xml file in values and add your drawables into an array like this

<integer-array name="images">
    <item>@drawable/drawable1</item>
    <item>@drawable/drawable2</item>
    <item>@drawable/drawable3</item>
</integer-array>

Then in your activity class add this

TypedArray images = getResources().obtainTypedArray(R.array.images);

// get resource id by random index i
images.getResourceId(i, -1)

Upvotes: 2

Dharmendra
Dharmendra

Reputation: 34006

Take one array of integer to store all drawables

int resIds = new int[]{R.drawable.s1, R.drawable.s2, .... R.drawable.s100};

Then calculate random index and pick drawable from that index

Random r = new Random();
int index = r.Next(resIds.length -1);
imageView.setImageResource(resIds[index]);

Upvotes: 1

Related Questions