WEB开发网
开发学院手机开发Android 开发 Android自定义长按事件 阅读

Android自定义长按事件

 2010-12-18 08:04:14 来源:WEB开发网   
核心提示:|| Math.abs(mLastMotionY-y) > TOUCH_SLOP) {//移动超过阈值,则表示移动了isMoved = true;removeCallbacks(mLongPressRunnable);}break;case MotionEvent.ACTION_UP://释放了removeCal

|| Math.abs(mLastMotionY-y) > TOUCH_SLOP) {

//移动超过阈值,则表示移动了

isMoved = true;

removeCallbacks(mLongPressRunnable);

}

break;

case MotionEvent.ACTION_UP:

//释放了

removeCallbacks(mLongPressRunnable);

break;

}

return true;

}

}

package chroya.fun;

import android.content.Context;

import android.view.MotionEvent;

import android.view.View;

import android.view.ViewConfiguration;

public class LongPressView2 extends View{

private int mLastMotionX, mLastMotionY;

//是否移动了

private boolean isMoved;

//长按的runnable

private Runnable mLongPressRunnable;

//移动的阈值

private static final int TOUCH_SLOP = 20;

public LongPressView2(Context context) {

super(context);

mLongPressRunnable = new Runnable() {

@Override

public void run() {

performLongClick();

}

};

}

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;

isMoved = false;

postDelayed(mLongPressRunnable, ViewConfiguration.getLongPressTimeout());

break;

case MotionEvent.ACTION_MOVE:

if(isMoved) break;

if(Math.abs(mLastMotionX-x) > TOUCH_SLOP

|| Math.abs(mLastMotionY-y) > TOUCH_SLOP) {

//移动超过阈值,则表示移动了

isMoved = true;

removeCallbacks(mLongPressRunnable);

}

break;

case MotionEvent.ACTION_UP:

//释放了

removeCallbacks(mLongPressRunnable);

break;

}

return true;

}

}

思路跟第一种差不多,不过,在移动超过阈值和释放之后,会将Runnable从事件队列中remove掉,长按事件也就不会再触发了。源码中实现长按的原理也基本如此。

工程见附件。


  点击下载:php?id=1362" rel="nofollow">源码下载

上一页  1 2 3 4 

Tags:Android 定义 事件

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接