一个view如何同时响应onTouch和onClick事件,这种情况很多,但是在网上搜了很长时间,大多数都是讲解如何区分onTouchEvent和onClick,onLongClick的调用顺序和流程.但是都没有讲到如何让onTouch事件和onClick事件共存.也就是说一个控件既能响应点击事件又能响应触摸事件.
首先声明,此博文参考的文章链接https://technicalsearch.iteye.com/blog/1972470 感谢前辈的智慧结晶.
值得说明的是解决的思路:在touch事件的onMove中判断手指的移动距离,当移动通过勾股定理算出<15px时,就把此事件当做是点击事件,当算出移动距离大于等于15px时就当做触摸事件处理
直接贴出代码,需要的朋友复制粘贴就可使用.
flSmall.setOnTouchListener(new View.OnTouchListener() { private int lastY; private int lastX; private float x1, x2; private float y1, y2; @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); int screenWidth = getResources().getDisplayMetrics().widthPixels; switch (action) { case MotionEvent.ACTION_DOWN: lastX = (int) event.getRawX(); lastY = (int) event.getRawY(); x1 = event.getRawX();//得到相对应屏幕左上角的坐标 y1 = event.getRawY(); break; case MotionEvent.ACTION_MOVE: int dx = (int) event.getRawX() - lastX; int dy = (int) event.getRawY() - lastY; int left = v.getLeft() + dx; int top = v.getTop() + dy; int right = v.getRight() + dx; int bottom = v.getBottom() + dy; if (left < 0) { left = 0; right = left + v.getWidth(); } if (right > screenWidth) { right = screenWidth; left = right - v.getWidth(); } if (top < 0) { top = 0; bottom = top + v.getHeight(); } if (bottom > getScreenHeight(MainActivity.this)) { bottom = getScreenHeight(MainActivity.this); top = bottom - v.getHeight(); } v.layout(left, top, right, bottom); lastX = (int) event.getRawX(); lastY = (int) event.getRawY(); break; case MotionEvent.ACTION_UP: x2 = event.getRawX(); y2 = event.getRawY(); Log.i("i", x1 + ",,," + y1 + ",,," + x2 + ",,," + y2); double distance = Math.sqrt(Math.abs(x1 - x2) * Math.abs(x1 - x2) + Math.abs(y1 - y2) * Math.abs(y1 - y2));//两点之间的距离 Log.d("i", "x1 - x2>>>>>>" + distance); if (distance < 15) { // 距离较小,当作click事件来处理 Log.d(TAG, "onTouch: 点击事件"); return false; } else { Log.d(TAG, "onTouch: 滑动事件"); return true; } } return false; } }); } public int getScreenHeight(Activity activity) { if (activity.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { return DisplayUtil.getScreenWidth(activity); } else { return DisplayUtil.getRealScreenHeight(activity); } }