Reputation: 910
I am currently doing my little project. I want to simply set 4 buttons in my APP and by pressing the button, I should keep doing the same thing till I release the button. ( For example, I need to use these 4 buttons to control my machine's direction.)
I've been trying few different methods, such as onTouch. However, In this method, I need to keep slightly move my finger so that I can keep doing the same thing. otherwise, it will stop. Also for onlongClicklistener and setpressed to true. None of them have the thing I want.
Can anyone tell me what methods I can call or the logic to implement this? Thank you so much! :)
Upvotes: 2
Views: 1303
Reputation: 196
I think onTouchListerner
will best suits for your requirement. Use thread for doing the work. On event ACTION_DOWN
start the thread and on event ACTION_UP
stop the thread.
((Button) findViewById(R.id.leftBtn)).setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
// start the thread
return true;
} else if(event.getAction() == MotionEvent.ACTION_UP){
// stop the thread
return true;
}
return false;
}
});
Hope this will help for you.
Upvotes: 1
Reputation: 31438
you can set the normal on click listener and inside start a thread, timer, backgroundtask, or something else that would periodically check if your button is pressed.
For example you could do it similarly to this:
final Button yourButton = (Button) view.findViewById(R.id.your_button);
long timerInterval = 1000; //one second
yourButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
if (yourButton.isPressed()) {
// do something (executing your code on button being pressed)
} else {
t.cancel();
}
}
}, 0, timerInterval);
}
});
This will execute your code every second the button is being pressed.
IMPORTANT: This presents the general idea, remember that the anonymous TimerTask
class will hold a strong reference to the yourButton
instance which is a subject to leak. You should be using a your_button
reference that will be "garbage-collected" if the View
is destroyed and inside the TimerTask
you should be checking if yourButton
is null
or not.
Upvotes: 2