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
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");
}
});