我想知道如何在android中随机选择一个按钮。例如,有4个按钮,我希望应用程序从它们中随机选择一个按钮并对其执行一些操作。这是我的代码:
Button start;
ImageButton btn1, btn2, btn3, btn4, btn5;
Random random = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory);
start = (Button)findViewById(R.id.button1);
start.setOnClickListener(this);
btn1 = (ImageButton)findViewById(R.id.imageButton1);
btn2 = (ImageButton)findViewById(R.id.imageButton2);
btn3 = (ImageButton)findViewById(R.id.imageButton3);
btn4 = (ImageButton)findViewById(R.id.imageButton4);
}
ImageButton[] all= {btn1, btn2, btn3, btn4};
@Override
public void onClick(View v) {
if (v == start)
{
btn5 = all[random.nextInt(all.length)];
btn5.setBackgroundColor(Color.RED);
}
}
如果我改变它,它可以完美地工作但是它只会是btn1而不是随机选择。
@Override
public void onClick(View v) {
if (v == start)
{
btn5 = btn1;
btn5.setBackgroundColor(Color.RED);
}
}
答案 0 :(得分:2)
您需要将此行放在onCreate()
方法中:
all= {btn1, btn2, btn3, btn4};
现在:
ImageButton[] all= {btn1, btn2, btn3, btn4};
它在所有按钮为空的承包商时间运行。在onCreate中,您为新变量分配按钮,但这不会改变ImageButton。另外你可以写道:
ImageButton[0] = (ImageButton)findViewById(R.id.imageButton1);
ImageButton[1] = (ImageButton)findViewById(R.id.imageButton2);
ImageButton[2] = (ImageButton)findViewById(R.id.imageButton3);
ImageButton[3] = (ImageButton)findViewById(R.id.imageButton4);
答案 1 :(得分:2)
all
必须设置 后设置btn1
等:否则它将是null
的数组。
btn1 = (ImageButton)findViewById(R.id.imageButton1);
btn2 = (ImageButton)findViewById(R.id.imageButton2);
btn3 = (ImageButton)findViewById(R.id.imageButton3);
btn4 = (ImageButton)findViewById(R.id.imageButton4);
all= {btn1, btn2, btn3, btn4}; //here
}
ImageButton[] all; //not here
答案 2 :(得分:0)
How do I generate random integers within a specific range in Java?
检查以上引用以生成随机数,然后使用
switch(number)
{
case 1:
button.performClick()
.....
}
答案 3 :(得分:0)
这样做
ImageButton[] all= {btn1, btn2, btn3, btn4};
Random rand = new Random();
ImageButton randomBtn = all[rand.nextInt(all.length)];
答案 4 :(得分:0)
我目前运行的代码如下:
Button start;
ImageButton btn1, btn2, btn3, btn4, btn5;
Random random;
int[] all;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
random = new Random();
start = (Button)findViewById(R.id.button1);
start.setOnClickListener(this);
btn1 = (ImageButton)findViewById(R.id.ImageButton01);
btn2 = (ImageButton)findViewById(R.id.ImageButton02);
btn3 = (ImageButton)findViewById(R.id.ImageButton03);
btn4 = (ImageButton)findViewById(R.id.ImageButton04);
all = new int[]{R.id.ImageButton01,R.id.ImageButton02,R.id.ImageButton03,R.id.ImageButton04};
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.button1)
{
int id = all[random.nextInt(all.length)];
findViewById(id).setBackgroundColor(Color.BLACK);
}
}