[英]Android: generate unrepeating random images
我在Android應用程序上制作不重復的隨機圖像時遇到了麻煩。
讓我們說在我的應用程序上我有這個前三部分,我有13張照片。 我需要一種方法從我有的@drawable上的13張照片中生成3張隨機圖像,但這3幅圖片應該彼此不同。
例如:它不能是TOP 3部分的img1,img1,img2或img1,img1,img1,但它應該是img1,img2,img3。
到目前為止,我手頭有這個方法:
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);
在我的布局上,我將TOP 3部分中的一個圖像ID指定為top1。 我還有頂部3的id top2和top3。 上面的代碼將查看我的可繪制圖像,其名稱為“img1.jpg”,“img2.jpg”,“img3.jpg”,“img4.jpg”等。
我願意接受任何解決方案。 如果有人可以即興創作我的代碼,那么3張圖片就不會完美相同。 但是如果你們中的任何一個人能夠用新方法提供更好的解決方案,那我就是開放的。
謝謝。
我建議你將你的圖像ID存儲在List
,使用shuffle並通過刪除來檢索第一個元素。
//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
某處)。
你可以嘗試這個來獲取隨機圖像...這對我有用.....`final int [] imageViews = {R.id.imageView2,R.id.imageView10,R.id.imageView3,R .id.imageView4,R.id.imageView5,R.id.imageView6,R.id.imageView8}; int [] photos = {R.drawable.aa,R.drawable.pp,R.drawable.ee,R.drawable.pp_blue,R.drawable.ll}; @Override protected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState); 的setContentView(R.layout.activity_main); //用於隨機化視圖Random rng = new Random(); List generated = new ArrayList(); for(int i = 0; i <5; i ++){while(true){Integer next = rng.nextInt(5); if(!generated.contains(next)){generated.add(next); ImageView iv =(ImageView)findViewById(imageViews [i]); iv.setImageResource(照片[下一個]); 打破; } //} ///隨機結束
}`
只是一個想法:
您可以將rndInt
存儲在地圖中並檢查if
map.containsKey(rndInt)
,否則獲取另一個隨機ID(並再次檢查新ID是否在地圖中), else
繼續正常流程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.