Here you are:
First of, you need to import the namespace that contains the random object:
import java.util.Random;
Then you have to take an object out of it
final Random rnd = new Random();
Now, all the action happens in your onCreate method, after you set your contentView:
// Reference the images
ImageView img1 = (ImageView) findViewById(R.id.imageView1);
ImageView img2 = (ImageView) findViewById(R.id.imageView2);
ImageView img3 = (ImageView) findViewById(R.id.imageView3);
ImageView img4 = (ImageView) findViewById(R.id.imageView4);
ImageView img5 = (ImageView) findViewById(R.id.imageView5);
ImageView img6 = (ImageView) findViewById(R.id.imageView6);
// Your images are named img_0.png to img_14.png
// For image 1
final String str = "img_" + rnd.nextInt(14);
img1.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getApplicationContext()))
);
// For image 2
str = "img_" + rnd.nextInt(14);
img2.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getApplicationContext()))
);
// ...
Now, where is the trick?
In this method:
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
I left out the lines of code for image 3 to 6, but they are the very same as for image 2.