[英]Show image randomly when button is clicked
我做了9個imagebuttons
和1個button
。
我只希望4個按鈕在單擊按鈕時顯示圖像,並且每次按鈕被隨機顯示,那怎么可能?
您可以創建一個包含圖像的src名稱的數組,並且可以使用
string imageArray = Name of yur images
int random = (int )(Math.random() * 9);
然后,您可以根據此隨機數為圖像按鈕圖像添加機會。
imgButton.setBackgroundResource(imageArray[random]);
我希望它是清楚和有用的。
嘗試這個
// add your image buttons to this list
ArrayList<ImageButton> allImageButtons = new ArrayList<ImageButton>();
allImageButtons.add(imgbtn1); //etc... for all 8 image buttons
然后在您的按鈕中單擊方法
Random rnd = new Random();
ArrayList<Integer> randomNumbers = new ArrayList<Integer>();
while (randomNumbers.size() < 4)
{
int num = rnd.nextInt(9);
if (!randomNumbers.contains(num))
randomNumbers.add(num);
}
for (int i=0;i<allImageButtons.size();i++)
{
if (randomNumbers.contains(i))
allImageButtons.get(i).setVisibility(View.VISIBLE);
else
allImageButtons.get(i).setVisibility(View.GONE);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.