Android 自定义长按事件

  1. public class LongPressView extends View{  
  2.     private int mLastMotionX, mLastMotionY;  
  3.     //是否移动了  
  4.     private boolean isMoved;  
  5.     //长按的runnable  
  6.     private Runnable mLongPressRunnable;  
  7.     //移动的阈值  
  8.     private static final int TOUCH_SLOP = 20;  
  9.   
  10.     public LongPressView(Context context) {  
  11.         super(context);  
  12.         mLongPressRunnable = new Runnable() {  
  13.               
  14.             @Override  
  15.             public void run() {               
  16.                 performLongClick();  
  17.             }  
  18.         };  
  19.     }  
  20.   
  21.     public boolean dispatchTouchEvent(MotionEvent event) {  
  22.         int x = (int) event.getX();  
  23.         int y = (int) event.getY();  
  24.           
  25.         switch(event.getAction()) {  
  26.         case MotionEvent.ACTION_DOWN:  
  27.             mLastMotionX = x;  
  28.             mLastMotionY = y;  
  29.             isMoved = false;  
  30.             postDelayed(mLongPressRunnable, ViewConfiguration.getLongPressTimeout());  
  31.             break;  
  32.         case MotionEvent.ACTION_MOVE:  
  33.             if(isMoved) break;  
  34.             if(Math.abs(mLastMotionX-x) > TOUCH_SLOP   
  35.                     || Math.abs(mLastMotionY-y) > TOUCH_SLOP) {  
  36.                 //移动超过阈值,则表示移动了  
  37.                 isMoved = true;  
  38.                 removeCallbacks(mLongPressRunnable);  
  39.             }  
  40.             break;  
  41.         case MotionEvent.ACTION_UP:  
  42.             //释放  
  43.             removeCallbacks(mLongPressRunnable);  
  44.             break;  
  45.         }  
  46.         return true;  
  47.     }  
  48. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值