user2997502
user2997502

Reputation: 23

How to make random images load in ImageView? (Android)

I'm a begginer Android Developer And in my app I want to make a random image load out of a list of images every time then app is launched. Genneraly, I want to use ImageView because its simple, but you have to mention what image to load in the layout file or main.XML.

I don't know how to do this so please help. :-)

Upvotes: 2

Views: 7819

Answers (1)

chinglun
chinglun

Reputation: 647

It's not required to set the image in the .xml file

Say, you have an ImageView in your layout (say its main.xml)

main.xml

<ImageView>
    android:id="@id+/myImageView"
</ImageView>

In your Activity

int[] images = new int[] {R.drawable.image01, R.drawable.image02, R.drawable.image03};

// Get the ImageView
setContent(R.layout.main);
ImageView mImageView = (ImageView)findViewById(R.id.myImageView);

// Get a random between 0 and images.length-1
int imageId = (int)(Math.random() * images.length);

// Set the image
mImageView.setBackgroundResource(images[imageId]);

Hope this helps (:

Edit

  1. The index of the image array should not be hard coded
  2. Corrected the syntax error. Thank you Tom for pointing it out :)

Upvotes: 7

Related Questions