I wrote a simple subclass of ImageView
that I want to use to detect double clicks on GridView
-items:
public class DoubleClickImageView extends ImageView {
public interface ClickListener {
void onSingleClick();
void onDoubleClick();
}
private ClickListener imageClickReceiver;
private GestureDetector gestureDetector;
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
// return super.onTouchEvent(event); does not work with gestureDetector
// return false; does not work with gestureDetector
return true; // works but breaks the rest of the application
}
public void setDoubleClickListener(ClickListener listener) {
imageClickReceiver = listener;
}
public DoubleClickImageView(Context cx, AttributeSet attrs) {
super(cx, attrs);
gestureDetector = new GestureDetector(cx, new InternalClickListener());
}
private class InternalClickListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
if (imageClickReceiver != null) {
imageClickReceiver.onSingleClick();
}
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
if (imageClickReceiver != null) {
imageClickReceiver.onDoubleClick();
}
return true;
}
@Override
public boolean onDown(MotionEvent event) {
//return true for onDown is required according to docs but does not help
return true;
}
}
}
The GridView
consists of Images that are displayed using this class.
The problem is that the double click detection works only when onTouchEvent
returns true
, otherwise the gestureDetector
does not detect any click event.
However, when I return true
in the onTouchEvent
, it breaks the rest of my application, since I have a global onTouchListener
to detect swipes over the whole GridView
and a multiple choice select mode with long press.
How can I solve this problem so that all of these three features work together?
Update: I was able to trace down the problem with debug logs. If the initial onTouchEvent-call (MotionEvent.ACTION_DOWN
) returns false,then the related follow-up-events are not delivered to the ImageView
. Therefore the GestureDetector can not make any sense of it, since it needs all related MotionEvents of a given gesture.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…