android - Detect touch press vs long press vs movement? -
i'm fiddling around android programming, have small problem detecting different touch events, namely normal touch press (press on screen , release right away), long press (touch screen , hold finger on it) , movement (dragging on screen).
what wanted have image (of circle) on screen can drag around. when press once (short/normal press) toast comes basic information it. when long press it, alertdialog list comes select different image (circle, rectangle or triangle).
i made custom view own ontouchlistener detect events , draw image in ondraw. ontouchlistener.ontouch goes this:
// has touch press started? private boolean touchstarted = false; // co-ordinates of image private int x, y; public boolean ontouch(view v, motionevent event) { int action = event.getaction(); if (action == motionevent.action_down) { touchstarted = true; } else if (action == motionevent.action_move) { // movement: cancel touch press touchstarted = false; x = event.getx(); y = event.gety(); invalidate(); // request draw } else if (action == motionevent.action_up) { if (touchstarted) { // touch press complete, show toast toast.maketext(v.getcontext(), "coords: " + x + ", " + y, 1000).show(); } } return true; }
the problem press doesn't quite work expected, because when casually touch screen detects tiny bit of movement , cancels touch press , moves around image instead.
i "hacked" around bit introducing new variable "mtouchdelay" set 0 on action_down, increase in move , if it's >= 3 in move execute "move" code. have feeling isn't way go.
i haven't found out how detect long press. culprit move seems trigger.
for example of want, see android application "dailystrip": shows image of comic strip. can drag if it's large screen. can tap once controls pop-up , long press options menu.
ps. i'm trying work on android 1.5, since phone runs on 1.5.
this code can distinguish between click , movement (drag, scroll). in ontouchevent set flag isonclick, , initial x, y coordinates on action_down. clear flag on action_move (minding unintentional movement detected can solved threshold const).
private float mdownx; private float mdowny; private final float scroll_threshold = 10; private boolean isonclick; @override public boolean ontouchevent(motionevent ev) { switch (ev.getaction() & motionevent.action_mask) { case motionevent.action_down: mdownx = ev.getx(); mdowny = ev.gety(); isonclick = true; break; case motionevent.action_cancel: case motionevent.action_up: if (isonclick) { log.i(log_tag, "onclick "); //todo onclick code } break; case motionevent.action_move: if (isonclick && (math.abs(mdownx - ev.getx()) > scroll_threshold || math.abs(mdowny - ev.gety()) > scroll_threshold)) { log.i(log_tag, "movement detected"); isonclick = false; } break; default: break; } return true; }
for longpress suggested above, gesturedetector way go. check q&a:
Comments
Post a Comment