【问题标题】:How to randomized a group of images in imageview in android studio?如何在android studio的imageview中随机化一组图像?
【发布时间】:2017-03-09 04:08:25
【问题描述】:

我是 android 开发的初学者,我正在为我的项目创建像 4Pics1Word 这样的游戏。 我想知道如何将图像随机化为 4。每个活动必须有 4 张图像,并且这些图像必须相互关联,因此,4 张图片 1 个单词。 所以我想我可以在每张图片上放置描述,然后将其随机化,然后使用控制语句来获取具有匹配描述的那 4 张图片。我只需要随机化它以随机化级别(因此每个应用程序不会有相同的连续级别)。有任何想法吗?谢谢你!

【问题讨论】:

  • 你有没有尝试过?如果你有,那么在你的问题中提到它,并告诉你在哪一步失败了。我们很多人都想帮助你,但请阅读How do I ask a good question。不管怎样,欢迎来到 StackOverflow :)

标签: java android random imageview sharedpreferences


【解决方案1】:

我会这样做:

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);
        }
    }
}

它所做的只是在列表中找到一张随机图片并检查它是否已被使用以及描述是否匹配。它将继续拉随机图片,直到尝试了所有图片或所有 ImageView 都被填满。自己没有尝试过,但代码应该可以工作。

另一个想法:最好将所有具有相同描述的图像放在自己的数组列表中。这样,您就可以从所述数组列表中随机抽取一张图片。例如:

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()));
}

【讨论】:

  • 嘿!非常感谢!我会试试的! :D
【解决方案2】:
// 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()))
        );

【讨论】:

  • 谢谢。但我需要一组 4 张相关图片来随机化。因此,假设我的游戏有 5 个活动。每个活动由 4 张相互关联的图片组成。所以我将使用20张图片。这 20 张图片将除以 5。每组有 4 张相互关联的图片。那么我要如何随机化这组图片呢?
  • 应用所有活动但在活动中更改图像名称的相同概念..例如,如果我只想在活动 A 中显示苹果图像,则意味着您的图像名称应该像 apple_0..apple_5..随机数 5。 ..then imagename = "apple_" + rnd.nextInt(N)
猜你喜欢
  • 2014-01-29
  • 2023-03-30
  • 1970-01-01
  • 2017-02-19
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
相关资源
最近更新 更多