In an application I\'m working on, I have the requirement that a user must click & hold a component for a period time before a certain action occurs.
I\'m curren
final boolean[] isLongPress = {false};
final int duration = 3000;
final Handler someHandler = new Handler();
final Runnable someCall = new Runnable() {
@Override
public void run() {
if(isLongPress[0]) {
// your code goes here
}
}
};
someButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int eventAction = event.getAction();
if(eventAction == MotionEvent.ACTION_DOWN){
isLongPress[0] = true;
someHandler.postDelayed(someCall, duration);
}
else if (eventAction == MotionEvent.ACTION_UP) {
isLongPress[0] = false;
someHandler.removeCallbacks(someCall);
}
return false;
}
});
For future reference, here is my implementation :)
public abstract class MyLongClickListener implements View.OnTouchListener {
private int delay;
private boolean down;
private Runnable callback;
private RectF mRect = new RectF();
public MyLongClickListener(int delay) {
this.delay = delay;
this.callback = new Runnable() {
@Override
public void run() {
down = false;
onLongClick();
}
};
}
public abstract void onLongClick();
@Override
public boolean onTouch(View v, MotionEvent e) {
if (e.getPointerCount() > 1) return true;
int action = e.getAction();
if (action == MotionEvent.ACTION_DOWN) {
down = true;
mRect.set(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.postDelayed(callback, delay);
return false;
} else if (action == MotionEvent.ACTION_MOVE) {
if (down && !mRect.contains(v.getLeft() + e.getX(), v.getTop() + e.getY())) {
v.removeCallbacks(callback);
down = false;
return false;
}
} else if (action == MotionEvent.ACTION_UP) {
if (down) {
v.removeCallbacks(callback);
v.performClick();
}
return true;
} else if (action == MotionEvent.ACTION_CANCEL) {
v.removeCallbacks(callback);
down = false;
}
return false;
}
}
Usage:
textView.setOnTouchListener(new MyLongClickListener(2000) {
@Override
public void onLongClick() {
System.err.println("onLongClick");
}
});