I am currently trying to write a memory game where there are 4 boxes and among the 4 boxes there will be 4 which are selected randomly. Then the users have to memorize them and input the 4 boxes in correct order.
However I am currently facing a problem. It seems like handler
only allows final variable
. This is my code:
private OnClickListener click1 = new OnClickListener() {
@Override
public void onClick(View v) {
final ImageButton[] all= {btn1, btn2, btn3, btn4};
for (int a=0;a<4;a++) {
handler1.postDelayed(new Runnable() { //start delay a
@Override
public void run() {
//actions start
btn5 = all[random.nextInt(all.length)];
btn5.setBackgroundColor(Color.RED);
handler1.postDelayed(new Runnable() { //start delay b
@Override
public void run() {
btn5.setBackgroundResource(R.drawable.btn_default_holo_dark);
}}, 500); //end delay b
//action end
}}, 1000*a ); //end delay a
}
}
};
I try to put 4 variable
inside to store the data of the btn5
but it doesn't work and it shows an error as a
must be final.
btn5 = all[random.nextInt(all.length)];
if (a==0) {ans1 = btn5;} //error
else if (a==1) {ans2 = btn5;} //error
else if (a==2) {ans3 = btn5;} //error
else if (a==3) {ans4 = btn5;} //error
btn5.setBackgroundColor(Color.RED);
Is there any method to allow my if else
statement? or is there any other method to allow me to store btn5
data in order?