Package COM. example. longpress;/*** @ author E-mail: chenshaohua2012@126.com * @ version Creation Time: 12:07:32 * class description */import android. content. context; import android. view. motionevent; import android. view. view; public class longpressview1 extends view {private int mlastmotionx, mlastmotiony; // whether the private Boolean ismoved is moved; // whether the private Boolean isreleased is released; // the counter, prevent the last longpress time from being shortened due to multiple clicks. privat E int mcounter; // long-pressed runnableprivate runnable mlongpressrunnable; // The moving threshold value is Private Static final int touch_slop = 20; Public longpressview1 (context) {super (context ); mlongpressrunnable = new runnable () {@ overridepublic void run () {system. out. println ("Thread"); system. out. println ("mcounter --- >>>" + mcounter); system. out. println ("isreleased --- >>>" + isreleased); system. out. println ("ismoved --- >>>" + ismove D); mcounter --; // If the counter is greater than 0, it indicates that the currently executed runnable is not generated in the last down. If (mcounter> 0 | isreleased | ismoved) return; callback mlongclick (); // callback duration event };} public Boolean dispatchtouchevent (motionevent event) {int x = (INT) event. getx (); int y = (INT) event. gety (); Switch (event. getaction () {Case motionevent. action_down: mlastmotionx = x; mlastmotiony = y; mcounter ++; isreleased = false; ismoved = false; postdelayed (mlongpressrunnable, 3000); // call the thread break after three seconds; case motionevent. action_move: If (ismoved) break; If (math. ABS (mlastmotionx-x)> touch_slop | math. ABS (mlastmotiony-y)> touch_slop) {// if the movement exceeds the threshold, ismoved = true;} break; Case motionevent is moved. action_up: // released isreleased = true; break;} return true ;}}
Public class longmainactivity extends activity {@ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); linearlayout. layoutparams layout = new layoutparams (layoutparams. fill_parent, layoutparams. fill_parent); view v = new longpressview1 (longmainactivity. this); V. setlayoutparams (layout); setcontentview (V); V. setonlongclicklistener (new view. onlongclicklistener () {@ overridepublic Boolean onlongclick (view v) {toast. maketext (longmainactivity. this, "abcdef", toast. length_short ). show (); Return false ;}});}}