I’m writing a puzzle game to learn developing Android Apps. But now I’m stuck on how to add images dynamically to the ImageViews in the layout file (see below). I’m trying to make a loop where I add a random image to each of the ImageViews. But I can’t find any examples on how to do this. My images are named the same as the ImageViews, only in lower case letters.
Or are there some other and better ways to solve this?
My code so far:
// Puzzle of 2x2 tiles
String[] sTiles = {"A0","A1","B0","B1"};
final Random myRandom = new Random();
// Random tiles
String tmp = null;
for (int i = 0; i < sTiles.length; ++i) {
tmp = sTiles[i];
int r = myRandom.nextInt(sTiles.length);
sTiles[i] = sTiles[r];
sTiles[r] = tmp;
}
// Lopp to add images randomly to the screen (layout/main.xml)
//for(i=0; i < sTiles.length; ++i) {
ImageView image = (ImageView) findViewById(R.id.B0);
image.setImageResource(R.drawable.a0);
//}
————— layout/main.xml ————
<TableRow>
<ImageView
android:id="@+id/A0"
android:layout_column="1" />
<ImageView
android:id="@+id/A1"
android:gravity="right" />
</TableRow>
<TableRow>
<ImageView
android:id="@+id/B0" />
<ImageView
android:id="@+id/B1" />
</TableRow>
Thanks, Sigurd!
Try setting up a few int arrays to store your drawable and widget IDs. It’s faster than using reflection to find them by name. Something like this should do the trick:
You may want to add some special handling if you want to ensure that all the ImageViews get unique images, but that should work as is.