I wanted to know how to randomly select a button in android. Like for example there got 4 button, I want the application to randomly choose a button from them and do some actions to it. Here is my code:
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);
}
}
If I change to this it work perfectly but then it will only be btn1 and not randomly select.
@Override
public void onClick(View v) {
if (v == start)
{
btn5 = btn1;
btn5.setBackgroundColor(Color.RED);
}
}