自定义的长按事件。

public class LongPressView extends View{private static final String TAG = "LongPressView";private int mLastMotionX, mLastMotionY;private boolean isMoved;//长按的runnableprivate Runnable mLongPressRunnable;//移动的阈值private static final int TOUCH_SLOP = 20;public LongPressView(final Context context) {super(context);mLongPressRunnable = new Runnable() {@Overridepublic void run() {Log.i(TAG, "mLongPressRunnable excuted");performLongClick();// 执行长按事件(如果有定义的话)}};}/* *  * 1)在down的时候,让一个Runnable在设定时间后执行, *      如果设定时间到了,没有移动超过定义的阈值,也没有释放,则触发长按事件 *  * 2)在移动超过阈值和释放之后,会将Runnable从事件队列中remove掉,长按事件也就不会再触发了 *  */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;/* * 将mLongPressRunnable放进任务队列中,到达设定时间后开始执行 * 这里的长按时间采用系统标准长按时间 */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;}}

Activity调用。
public class MainActivity extends Activity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);                View mLongPressView = new LongPressView(this);        mLongPressView.setOnLongClickListener(new OnLongClickListener() {@Overridepublic boolean onLongClick(View v) {Toast.makeText(MainActivity.this,"I got a long press!", Toast.LENGTH_SHORT).show();return false;}});        setContentView(mLongPressView);    }}

更多相关文章

  1. Android在ListView中获得对应行的button点击事件
  2. android ListView的常用事件
  3. 事件总线EventBus Android开源库的使用
  4. android listview的item里面的imageview的点击事件
  5. Notification 事件 使用
  6. android点击手机返回键触发事件
  7. android home键点击事件处理
  8. Android监听事件

随机推荐

  1. Android(安卓)使用grade实现Android(安卓
  2. Android开机自启动
  3. Android(安卓)Studio 使用小结
  4. zbar android sdk源码编译
  5. android 线性布局几个属性
  6. Android(安卓)3D 编程:索引
  7. Android中图片压缩分析(下)
  8. 如何调试跟踪Android源代码
  9. Android常用布局:线性布局和相对布局
  10. 初涉Android蓝牙开发