setOnLongClickListener是android自带的长按事件,但有时在自定义view中我们需要点击我们绘制的图形,
这就需要自定义一个长按事件。
首先是自定义view的实现:
package com.example.hxl.longpressview; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; /** * Created by hxl on 2017/4/5 at haiChou. */ public class LongPressView extends View{ /** * 上一次点击的的坐标 */ private float lastX; private float lastY; /** * 长按坐标 */ private float longPressX; private float longPressY; /** * 是否移动 */ private boolean isMove; /** * 滑动的阈值 */ private static final int TOUCH_SLOP = 20; private Runnable runnable; public LongPressView(Context context) { this(context,null); } public LongPressView(Context context, AttributeSet attrs) { this(context, attrs,0); } public LongPressView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { runnable = new Runnable() { @Override public void run() { //执行长按点击事件的逻辑代码 Log.e("LongPressView", "run: "+"长按点击了" ); } }; } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: isMove = false; lastX = x; lastY = y; postDelayed(runnable, ViewConfiguration.getLongPressTimeout()); break; case MotionEvent.ACTION_MOVE: if (isMove){ break; } if (Math.abs(lastX-x) > TOUCH_SLOP || Math.abs(lastY-y) > TOUCH_SLOP){ //移动超过了阈值,表示移动了 isMove = true; //移除runnable removeCallbacks(runnable); } break; case MotionEvent.ACTION_UP: removeCallbacks(runnable); break; } return true; } }布局文件:
<com.example.hxl.longpressview.LongPressViewandroid:id="@+id/press_id"android:layout_width="match_parent" android:layout_height="match_parent" android:background="@mipmap/ic_launcher" />
为了便于activity或fragment的调用,设置对外访问的接口:/** * 设置对外访问的长按监听接口 */ public interface OnMyLongClickListener{ void onMyLongClickCoordinate(float x,float y); } private OnMyLongClickListener onMyLongClickListener; public void setOnMyLongClickListener(OnMyLongClickListener onMyLongClickListener) { this.onMyLongClickListener = onMyLongClickListener; }//在init()方法中调用private void init() { runnable = new Runnable() { @Override public void run() { //执行长按点击事件的逻辑代码longPressX = lastX;
longPressY = lastY;} }; }onMyLongClickListener.onMyLongClickCoordinate(longPressX,longPressY);