DoubleTap in android [duplicate]
I need to create a small text area.Within that text area when i double click,it will move to next activity.How could i do this?
Solution 1:
If you do the setup right, the OnDoubleTapListener
, within the GestureListener
is very useful. You dont need to handle each single tap and count time in between. Instead let Android handle for you what a tap, a double-tap, a scroll or fling might be. With the helper class SimpleGestureListener
that implements the GestureListener
and OnDoubleTapListener
you dont need much to do.
findViewById(R.id.touchableText).setOnTouchListener(new OnTouchListener() {
private GestureDetector gestureDetector = new GestureDetector(Test.this, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTap(MotionEvent e) {
Log.d("TEST", "onDoubleTap");
return super.onDoubleTap(e);
}
... // implement here other callback methods like onFling, onScroll as necessary
});
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("TEST", "Raw event: " + event.getAction() + ", (" + event.getRawX() + ", " + event.getRawY() + ")");
gestureDetector.onTouchEvent(event);
return true;
}
});
Note: I tested around quite a while to find out, what the right mixture of return true
and return false
is. This was the really tricky part here.
Another note: When you test this, do it on a real device, instead of the emulator. I had real trouble getting the mouse fast enough to create an onFling event. Real fingers on real devices seem to be much faster.
Solution 2:
A better alternative is to create a lightweight Abstract Class
public abstract class DoubleClickListener implements OnClickListener {
private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds
long lastClickTime = 0;
@Override
public void onClick(View v) {
long clickTime = System.currentTimeMillis();
if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
onDoubleClick(v);
lastClickTime = 0;
} else {
onSingleClick(v);
}
lastClickTime = clickTime;
}
public abstract void onSingleClick(View v);
public abstract void onDoubleClick(View v);
}
And use it like
view.setOnClickListener(new DoubleClickListener() {
@Override
public void onSingleClick(View v) {
}
@Override
public void onDoubleClick(View v) {
}
});
Solution 3:
very simple logic use below code
boolean firstTouch = false;
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == event.ACTION_DOWN){
if(firstTouch && (Helper.getCurrentTimeInMilliSeconds() - time) <= 300) {
//do stuff here for double tap
Log.e("** DOUBLE TAP**"," second tap ");
firstTouch = false;
} else {
firstTouch = true;
time = Helper.getCurrentTimeInMilliSeconds();
Log.e("** SINGLE TAP**"," First Tap time "+time);
return false;
}
}
return true;
}