Reputation: 217
In my previous question Make button method if button clicked or not cliked, i found my answer like this :
Handler visibilityToggler;
Runnable visivilityRunnable;
visibilityToggler = new Handler();
visivilityRunnable = new Runnable() {
@Override
public void run() {
// isUserClickedButton is used to keep record if user has pressed button within 1 sec
// keep isUserClickedButton = true for first time as it will run
if (!isUserClickedButton) {
// user not pressed button
Toast.makeText(context,"You are not pressed the Button",Toast.LENGHT_LONG).show();
}
// toggle visibility
Random generator = new Random();
number = generator.nextInt(16);
for (int i = 0; i < buttons.length; i++) {
if (i == number)
buttons[i].setVisibility(View.VISIBLE);
else
buttons[i].setVisibility(View.INVISIBLE);
}
// again start the visibility
visibilityToggler.postDelayed(visivilityRunnable,1000);
// make it false as visibility is toggled and we want to track button pressed from start
isUserClickedButton = false;
}
};
visibilityToggler.postDelayed(visivilityRunnable,1000);
Now my question is: How to stop a Runnable?
Can anyone can give a code sample?
UPDATE :
i had use the removecallbacks() on a button
public void onClick(View v){
visibilityToggler.removeCallbacks(visivilityRunnable);
}
but the runnable not stop, anyone can help?
Upvotes: 0
Views: 145
Reputation: 2668
I'm not sure if do you want to break the loop , but if i understand you i would suggest you to make a static boolean variable and stop it whenever you want
public static boolean isWorking=true;
for (int i = 0; i < buttons.length; i++) {
if(isWork){
if (i == number)
buttons[i].setVisibility(View.VISIBLE);
else
buttons[i].setVisibility(View.INVISIBLE);
}else break;}
now if you want to break the loop just change isWork
to false
Upvotes: 1
Reputation:
Define the runnable outside the handler. Then call handler.removeCallbacks(visivilityRunnable);
where you want to stop the handler.
Upvotes: 0