While loop in setOnTouchListener
-
21-12-2019 - |
Question
I want to do some action when button is pressed and stop those action when button is releasd. I have used the following code but it does not work. you may check my code here-
ok = (Button)findViewById(R.id.button1);
ok.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
my_var=true;
if (event.getAction() == MotionEvent.ACTION_DOWN) {
while(my_var) do_something();
}else if (event.getAction() == MotionEvent.ACTION_UP) {
my_var=false;
}
return true;
}
});
Is there any alternative solution for the above. Thanx in advance.
Solution
I think what you want is an AutoRepeatButton
Basically it's a class that extends Button
and adds some scheduled callbacks (you can adjust the interval) that happen as long as the ACTION_DOWN
MotionEvent
is occurring.
There are a few implementations floating around but I like the following one the best:
OTHER TIPS
To achieve so, you have to set my_var to false somewhere in the do_something method.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow