问题
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. :-)
回答1:
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
- The index of the image array should not be hard coded
- Corrected the syntax error. Thank you Tom for pointing it out :)
来源:https://stackoverflow.com/questions/20008842/how-to-make-random-images-load-in-imageview-android