安卓产生unrepeating随机图像 [英] Android: generate unrepeating random images

查看:175
本文介绍了安卓产生unrepeating随机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在我的Andr​​oid应用程序使得unrepeating随机图像的麻烦。

I'm having trouble in making unrepeating random images on my Android App.

让我的应用程序说我有这TOP 3段,我有13张图片。我需要一种方法来对@drawable我有生成从13图片3随机图像,但3张应彼此不同。

Let's say on my App I have this TOP 3 Sections, and I have 13 pictures. I need a method to generate 3 random images from the 13 pics on @drawable I have, but the 3 pictures should be different from one another.

例如:它不能IMG1,IMG1,IMG2或IMG1,IMG1,IMG1上的前3节,但它应该是IMG1,IMG2,IMG3

For example: it can't be img1,img1,img2 or img1,img1,img1 on the TOP 3 section but it should be img1,img2,img3.

到目前为止,我手上有此方法:

So far, I have this method in hand:

final Button imgView = (Button)findViewById(R.id.top1);
        Random rand = new Random();            
        int rndInt = rand.nextInt(13) + 1; 
        String imgName = "img" + rndInt;
        int id = getResources().getIdentifier(imgName, "drawable", getPackageName());  
        imgView.setBackgroundResource(id);

在我的布局,我在指定的前3节为TOP1的形象标识之一。我仍然有ID TOP2,并为TOP3前3部分。以上code将查找我的绘制图像,其中有名称img1.jpg','img2.jpg','img3.jpg','img4.jpg等。

On my layout, I specified one of the image ID on the TOP 3 section as top1. I still have the id top2, and top3 for the TOP 3 section. The above code will look up to my drawable images, which have the names 'img1.jpg', 'img2.jpg', 'img3.jpg' , 'img4.jpg', etc.

我接受任何一种解决方案。如果有人可以即兴我的code所以3张照片会不会与对方那将是完美的一样。但是,如果你们能提供一个新的方法,更好的解决方案,我打开它。

I'm open to any kind of solution. If somebody could improvise my code so 3 pictures won't be the same with each other that would be perfect. But if any of you can offer a better solution with a new method, I'm open for it.

感谢您。

推荐答案

我建议你到你的映像ID存储在列表,使用<一个href=\"http://developer.android.com/reference/java/util/Collections.html#shuffle%28java.util.List%3C?%3E,%20java.util.Random%29\"相对=nofollow>洗牌
并通过删除检索的第一个元素。

I'd suggest you to store your image ids in List, use shuffle and retrieve the first element by removing.

//the initial list of images
final List<String> images = new ArrayList<String>();
for (int i=1; i<=13; i++){
images.add("img"+i);
}
//the method that retrieves random value
Collections.shuffle(images, new Random());
String randomImage = images.remove(0);

编辑:

//this code should be inoked on every image add
final Button imgView = (Button)findViewById(R.id.top1);
Collections.shuffle(images, new Random());
String imgName = images.remove(0);
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());  
imgView.setBackgroundResource(id);

应进行一次名单的初始化,外面的图像添加方法(介于的onCreate 可能。

这篇关于安卓产生unrepeating随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆