Reputation: 33
I'm a beginner on android development and I am creating a game like 4Pics1Word for my project. I'm wondering on how can I randomized the images by 4. Every activities must have 4 images and those images must be related to each other, thus, 4 pics 1 word. So I'm thinking I can put descriptions on each image and then randomized it then use a control statement in order to get those 4 pictures with matching descriptions. I only need to randomized it in order to randomized the levels (so each application will not have the same consecutive levels). Any ideas? Thank youuuu!
Upvotes: 0
Views: 1016
Reputation: 640
I would do something like this:
public void start() {
MyImage[] images = /* a list of your images */
ImageView[] imageViews = /* a list of your imageViews (in this case, 4)*/
fillImageViews(/* the desc */, imageViews, images);
}
private class MyImage() {
Drawable image;
String desc;
public MyImage(Drawable img, String description) {
image = img;
desc = description;
}
}
public void fillImageViews(String desc, ImageView[] views, MyImage[] images) {
ArrayList<Integer> usedIndexs = new ArrayList();
Random rand = new Random();
for (ImageView v : views) {
while (usedIndexs.size() < images.length) {
int index = rand.nextInt(images.length);
if (images[index].desc.equals(desc) && !usedIndexs.contains(index)) {
//description matches
v.setImageDrawable(images[index].image);
usedIndexs.add(index);
break;
}
usedIndexs.add(index);
}
}
}
All it does is find a random picture in a list and checks to see if it has been used yet and if the description matches. It will keep pulling random pictures until it has tried them all or all the ImageViews get filled. Haven't tried it myself but the code should work.
Another Idea: It might be better to have all Images of the same description in it own arraylist. That way you can just pull a random picture from the said arraylist. ex:
ArrayList<Drawable> catPics = new ArrayList();
//add cat pics here
ArrayList<Drawable> dogPics = new ArrayList();
//add dogs pics here
//And now you could make function to pull the pictures
public Drawable getRandomPicture(ArrayList<Drawable> imgs) {
return imgs.get(new Random.nextInt(imgs.size()));
}
Upvotes: 1
Reputation: 13358
// In drwable folder your imagename like img_0,img_1,img_2.....img_N
String imagename = "img_" + rnd.nextInt(N);// N is Maximum random number
imageView.setImageDrawable(
getResources().getDrawable(getResourceID(imagename, "drawable",
getApplicationContext()))
);
Upvotes: 1