Reputation: 53
I am creating an android application and have run into a problem.
There is 12 buttons. A button is to change color and then the user has one second to click the button, otherwise the button changes back to the original color and a different button changes color.
I would like to repeat this until the user misses a certain amount of button clicks.
I have discovered how to do the changing in colors, however I am not sure how to do an infinite loop in android or how to wait for one second.
Thanks for your help. This is my first attempt at an android application.
Upvotes: 0
Views: 1340
Reputation: 2377
You can implement a timer by posting a Runnable object to run on a Handler with a specified delay. If you don't stop it from running, then the Runnable executes. However, you can also stop it from running before that:
private static final long ONE_SECOND = 1000L;
private static final int MISS_LIMIT = 10;
int misses = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
final Handler handler = new Handler();
final Runnable timer = new Runnable() {
@Override
public void run() {
// user too late: increment miss counter
if (++misses >= MISS_LIMIT) {
//TODO miss limit reached
finish(); // close this activity
}
}
};
final View btn1 = findViewById(R.id.button1);
final View btn2 = findViewById(R.id.button2);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// change color of other button, and start timer
btn2.setBackgroundResource(R.color.new_color);
handler.removeCallbacks(timer);
handler.postDelayed(timer, ONE_SECOND);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// user clicked button in time: restore color and stop timer
btn2.setBackgroundResource(R.color.orig_color);
handler.removeCallbacks(timer);
}
});
}
Upvotes: 1
Reputation: 2138
Firstly create a method something like this to change the color of button..
public void changeButton(int i){
switch (i) {
case 0:
button0.setClickable(true);
button0.setBackgroundResource(color1);
break;
case 1:
button0.setClickable(false);
button0.setBackgroundResource(color2);
button1.setClickable(true);
button1.setBackgroundResource(color1);
break;
case 2:
button1.setClickable(false);
button1.setBackgroundResource(color2);
button2.setClickable(true);
button2.setBackgroundResource(color1);
break;
.....
case 11:
button10.setClickable(false);
button10.setBackgroundResource(color2);
button11.setClickable(true);
button11.setBackgroundResource(color1);
break;
default:
break;
}
}
then you can implement a Runnable with some delay to call that method in loop like this..
Handler handler=new Handler();
int j=0;
final Runnable r = new Runnable()
{
public void run()
{
changeButton(j);
j++;
// next button color change
if(j<12){
handler.postDelayed(this, 1000);
}
else{
j=0;
handler.postDelayed(this, 1000);
}
}
};
handler.post(r)
Upvotes: 0