欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android触摸事件的应用详解

程序员文章站 2023-11-27 12:06:16
前言 上一篇讲了android触摸事件的传递机制,具体可以看这里初识android触摸事件传递机制。既然知道android中触摸事件的传递分发,那么它能解决什么样的问题,...

前言

上一篇讲了android触摸事件的传递机制,具体可以看这里初识android触摸事件传递机制。既然知道android中触摸事件的传递分发,那么它能解决什么样的问题,在我们实际开发中如何应用,这点很重要,知道原理是为了解决问题而准备的。这篇文章的核心讲的如何解决view的滑动冲突,这个问题在日常开发中很常见,比如内部嵌套fragment视图是左右滑动,外部用一个scrollview来包含,可以上下滑动,如果不进行滑动冲突处理的话,就会造成外部滑动方向和内部滑动方向不一致。

目录

常见的滑动冲突场景
滑动冲突的处理规则
外部拦截法
内部拦截法
小结

常见的滑动冲突场景

常见的滑动冲突场景可以简单分为以下三种:

场景1:外部滑动方向和内部滑动方向不一致
场景2:外部滑动方向和内部滑动方向一致
场景3:上面两种情况的嵌套

如图:

Android触摸事件的应用详解

场景1,主要是将viewpager和fragment配合使用所组成的页面滑动效果,主流应用几乎都会使用这个效果。在这个效果中可以通过左右滑动来切换页面,而每个页面内部往往又是一个listview,所以就造成了滑动冲突,但是在viewpager内部处理了这种滑动冲突,因此在采用viewpager时我们就无须关注这个问题,而如果把viewpager换成scrollview,那就必须自己手动处理,不然造成的结果就是内外两层只能一层能够滑动。

场景2,就复杂一点,当内外两层都在同一个方向可以滑动的时候,显然存在逻辑问题。因为当手指开始滑动的时候,系统无法知道用户到底是想让哪一层滑动,所以当手指滑动的时候就会出现问题,要么只有一层滑动,要么就是内外两层都滑动但很卡顿。

场景3,是场景1和场景2两种情况的嵌套,显得更复杂了。比如外部有一个slidemenu效果,内部有一个viewpager,viewpager的每一个页面中又是一个listview。虽然场景3滑动冲突看起来很复杂,但都是几个单一的滑动冲突的叠加,因此需要一一拆解开来即可。

滑动冲突的处理规则

一般来说,不管滑动冲突有多么复杂,它都有既定的规则,根据这些规则我们就可以选择合适的方法去处理。

对于场景1,它的处理规则就是:当用户左右滑动时,需要让外部的view拦截点击事件,当用户上下滑动,需要让内部view拦截点击事件。具体来说就是根据滑动是水平滑动还是竖直滑动来判断到底是由谁来拦截事件。

如图:

Android触摸事件的应用详解

简单来说,就是根据水平方向和竖直方向的距离差来判断,如果是dx>dy,那么则是水平滑动,如果是dy>dx,那么则是竖直滑动。

场景2,则是比较特殊,它无法根据滑动的角度,距离差以及速度差来做判断。这个时候就需要从业务上找到突破点,比如,当处于某种状态时需要外部view响应用户的滑动,而处于另外一种状态时需要内部view来响应view的滑动

对于场景3的话,它的滑动规则也更复杂,和场景2一样,同样是从业务上找到突破点。

外部拦截法

外部拦截法是指点击事件都是先经过父容器的拦截处理,如果父容器需要此事件就拦截,如果不需要此事件,就不拦截了,这样就可以解决滑动冲突的问题,外部拦截法需要重写父容器的onintercepttouchevent方法,在内部做相应的拦截即可,伪代码如下:

 @override
 public boolean onintercepttouchevent(motionevent event) {
 boolean intercepted = false;
 int x = (int) event.getx();
 int y = (int) event.gety();

 switch (event.getaction()) {
 case motionevent.action_down: {
  intercepted = false;
  break;
 }
 case motionevent.action_move: {
  if (父容器需要点击当前事件) {
  intercepted = true;
  } else {
  intercepted = false;
  }
  break;
 }
 case motionevent.action_up: {
  intercepted = false;
  break;
 }
 default:
  break;
 }
 mlastxintercept = x;
 mlastyintercept = y;

 return intercepted;
 }

首先action_down这个事件,父容器必须返回false,这样保证后续move和up的事件可以传递给子view,根据move事件来决定是否拦截,如果父容器拦截就返回true,否则返回false。

实现一个自定义类似viewpager的控件,嵌套listview的效果,源代码如下:

public class horizontalscrollviewex extends viewgroup {
 private static final string tag = "horizontalscrollviewex";

 private int mchildrensize;
 private int mchildwidth;
 private int mchildindex;

 // 分别记录上次滑动的坐标
 private int mlastx = 0;
 private int mlasty = 0;
 // 分别记录上次滑动的坐标(onintercepttouchevent)
 private int mlastxintercept = 0;
 private int mlastyintercept = 0;

 private scroller mscroller;  //弹性滑动对象
 private velocitytracker mvelocitytracker; //追踪滑动速度

 public horizontalscrollviewex(context context) {
 super(context);
 init();
 }

 public horizontalscrollviewex(context context, attributeset attrs) {
 super(context, attrs);
 init();
 }

 public horizontalscrollviewex(context context, attributeset attrs,
  int defstyle) {
 super(context, attrs, defstyle);
 init();
 }

 private void init() {
 mscroller = new scroller(getcontext());
 mvelocitytracker = velocitytracker.obtain();
 }

 @override
 public boolean onintercepttouchevent(motionevent event) {
 boolean intercepted = false;
 int x = (int) event.getx();
 int y = (int) event.gety();

 switch (event.getaction()) {
 case motionevent.action_down: {
  intercepted = false;
  if (!mscroller.isfinished()) {
  mscroller.abortanimation();
  intercepted = true;
  }
  break;
 }
 case motionevent.action_move: {
  int deltax = x - mlastxintercept;
  int deltay = y - mlastyintercept;
  if (math.abs(deltax) > math.abs(deltay)) {
  intercepted = true;
  } else {
  intercepted = false;
  }
  break;
 }
 case motionevent.action_up: {
  intercepted = false;
  break;
 }
 default:
  break;
 }

 log.d(tag, "intercepted=" + intercepted);
 mlastx = x;
 mlasty = y;
 mlastxintercept = x;
 mlastyintercept = y;

 return intercepted;
 }

 @override
 public boolean ontouchevent(motionevent event) {
 mvelocitytracker.addmovement(event);
 int x = (int) event.getx();
 int y = (int) event.gety();
 switch (event.getaction()) {
 case motionevent.action_down: {
  if (!mscroller.isfinished()) {
  mscroller.abortanimation();
  }
  break;
 }
 case motionevent.action_move: {
  int deltax = x - mlastx;
  scrollby(-deltax, 0);
  break;
 }
 case motionevent.action_up: {
  int scrollx = getscrollx();
  mvelocitytracker.computecurrentvelocity(1000);
  float xvelocity = mvelocitytracker.getxvelocity();
  if (math.abs(xvelocity) >= 50) {
  mchildindex = xvelocity > 0 ? mchildindex - 1 : mchildindex + 1;
  } else {
  mchildindex = (scrollx + mchildwidth / 2) / mchildwidth;
  }
  mchildindex = math.max(0, math.min(mchildindex, mchildrensize - 1));
  int dx = mchildindex * mchildwidth - scrollx;
  smoothscrollby(dx, 0);
  mvelocitytracker.clear();
  break;
 }
 default:
  break;
 }

 mlastx = x;
 mlasty = y;
 return true;
 }

 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
 super.onmeasure(widthmeasurespec, heightmeasurespec);
 int measuredwidth = 0;
 int measuredheight = 0;
 final int childcount = getchildcount();
 measurechildren(widthmeasurespec, heightmeasurespec);

 int widthspacesize = measurespec.getsize(widthmeasurespec);
 int widthspecmode = measurespec.getmode(widthmeasurespec);
 int heightspacesize = measurespec.getsize(heightmeasurespec);
 int heightspecmode = measurespec.getmode(heightmeasurespec);
 if (childcount == 0) {
  setmeasureddimension(0, 0);
 } else if (heightspecmode == measurespec.at_most) {
  final view childview = getchildat(0);
  measuredheight = childview.getmeasuredheight();
  setmeasureddimension(widthspacesize, childview.getmeasuredheight());
 } else if (widthspecmode == measurespec.at_most) {
  final view childview = getchildat(0);
  measuredwidth = childview.getmeasuredwidth() * childcount;
  setmeasureddimension(measuredwidth, heightspacesize);
 } else {
  final view childview = getchildat(0);
  measuredwidth = childview.getmeasuredwidth() * childcount;
  measuredheight = childview.getmeasuredheight();
  setmeasureddimension(measuredwidth, measuredheight);
 }
 }

 @override
 protected void onlayout(boolean changed, int l, int t, int r, int b) {
 int childleft = 0;
 final int childcount = getchildcount();
 mchildrensize = childcount;

 for (int i = 0; i < childcount; i++) {
  final view childview = getchildat(i);
  if (childview.getvisibility() != view.gone) {
  final int childwidth = childview.getmeasuredwidth();
  mchildwidth = childwidth;
  childview.layout(childleft, 0, childleft + childwidth,
   childview.getmeasuredheight());
  childleft += childwidth;
  }
 }
 }

 private void smoothscrollby(int dx, int dy) {
 mscroller.startscroll(getscrollx(), 0, dx, 0, 500);
 invalidate();
 }

 @override
 public void computescroll() {
 if (mscroller.computescrolloffset()) {
  scrollto(mscroller.getcurrx(), mscroller.getcurry());
  postinvalidate();
 }
 }

 @override
 protected void ondetachedfromwindow() {
 mvelocitytracker.recycle();
 super.ondetachedfromwindow();
 }
}

这个情况的拦截条件就是父容器在滑动过程中水平距离差比垂直距离差大,那么就进行拦截,否则就不拦截,继续传递事件。

内部拦截法

内部拦截法是指父容器不拦截任何事件,所有的事件都传递给子元素,如果子元素需要此事件就直接消耗掉,否则就交给父容器进行处理,这种方法和android中的事件分发机制不一致,需要配合requestdisallowintercepttouchevent方法才能正常工作,使用起来较外部拦截法复杂。伪代码如下:

 @override
 public boolean dispatchtouchevent(motionevent event) {
 int x = (int) event.getx();
 int y = (int) event.gety();

 switch (event.getaction()) {
 case motionevent.action_down: {
  mhorizontalscrollviewex2.requestdisallowintercepttouchevent(true);
  break;
 }
 case motionevent.action_move: {
  int deltax = x - mlastx;
  int deltay = y - mlasty;
  if (父容器需要此类点击事件) {
  mhorizontalscrollviewex2.requestdisallowintercepttouchevent(false);
  }
  break;
 }
 case motionevent.action_up: {
  break;
 }
 default:
  break;
 }

 mlastx = x;
 mlasty = y;
 return super.dispatchtouchevent(event);
 }

当子元素调用requestdisallowintercepttouchevent(false)方法时,父元素才能继续拦截所需的事件。

前面是用自定义类似的viewpager,现在重写一个listview,我们可以自定义一个listview,叫做listviewex,然后对内部拦截法的模板代码进行修改即可。

public class listviewex extends listview {
 private static final string tag = "listviewex";

 private horizontalscrollviewex2 mhorizontalscrollviewex2;

 // 分别记录上次滑动的坐标
 private int mlastx = 0;
 private int mlasty = 0;

 public listviewex(context context) {
 super(context);
 }

 public listviewex(context context, attributeset attrs) {
 super(context, attrs);
 }

 public listviewex(context context, attributeset attrs, int defstyle) {
 super(context, attrs, defstyle);
 }

 public void sethorizontalscrollviewex2(
  horizontalscrollviewex2 horizontalscrollviewex2) {
 mhorizontalscrollviewex2 = horizontalscrollviewex2;
 }

 @override
 public boolean dispatchtouchevent(motionevent event) {
 int x = (int) event.getx();
 int y = (int) event.gety();

 switch (event.getaction()) {
 case motionevent.action_down: {
  mhorizontalscrollviewex2.requestdisallowintercepttouchevent(true);
  break;
 }
 case motionevent.action_move: {
  int deltax = x - mlastx;
  int deltay = y - mlasty;
  log.d(tag, "dx:" + deltax + " dy:" + deltay);
  if (math.abs(deltax) > math.abs(deltay)) {
  mhorizontalscrollviewex2.requestdisallowintercepttouchevent(false);
  }
  break;
 }
 case motionevent.action_up: {
  break;
 }
 default:
  break;
 }

 mlastx = x;
 mlasty = y;
 return super.dispatchtouchevent(event);
 }
}

同时对于包含listviewex外部布局进行修改,在onintercepttouchevent事件上不进行拦截

public class horizontalscrollviewex2 extends viewgroup {
 private static final string tag = "horizontalscrollviewex2";

 private int mchildrensize;
 private int mchildwidth;
 private int mchildindex;
 // 分别记录上次滑动的坐标
 private int mlastx = 0;
 private int mlasty = 0;

 // 分别记录上次滑动的坐标(onintercepttouchevent)
 private int mlastxintercept = 0;
 private int mlastyintercept = 0;

 private scroller mscroller;
 private velocitytracker mvelocitytracker;

 public horizontalscrollviewex2(context context) {
 super(context);
 init();
 }

 public horizontalscrollviewex2(context context, attributeset attrs) {
 super(context, attrs);
 init();
 }

 public horizontalscrollviewex2(context context, attributeset attrs,
  int defstyle) {
 super(context, attrs, defstyle);
 init();
 }

 private void init() {
 mscroller = new scroller(getcontext());
 mvelocitytracker = velocitytracker.obtain();
 }

 @override
 public boolean onintercepttouchevent(motionevent event) {
 int x = (int) event.getx();
 int y = (int) event.gety();
 int action = event.getaction();
 if (action == motionevent.action_down) {
  mlastx = x;
  mlasty = y;
  if (!mscroller.isfinished()) {
  mscroller.abortanimation();
  return true;
  }
  return false;
 } else {
  return true;
 }
 }

 @override
 public boolean ontouchevent(motionevent event) {
 log.d(tag, "ontouchevent action:" + event.getaction());
 mvelocitytracker.addmovement(event);
 int x = (int) event.getx();
 int y = (int) event.gety();
 switch (event.getaction()) {
 case motionevent.action_down: {
  if (!mscroller.isfinished()) {
  mscroller.abortanimation();
  }
  break;
 }
 case motionevent.action_move: {
  int deltax = x - mlastx;
  int deltay = y - mlasty;
  log.d(tag, "move, deltax:" + deltax + " deltay:" + deltay);
  scrollby(-deltax, 0);
  break;
 }
 case motionevent.action_up: {
  int scrollx = getscrollx();
  int scrolltochildindex = scrollx / mchildwidth;
  log.d(tag, "current index:" + scrolltochildindex);
  mvelocitytracker.computecurrentvelocity(1000);
  float xvelocity = mvelocitytracker.getxvelocity();
  if (math.abs(xvelocity) >= 50) {
  mchildindex = xvelocity > 0 ? mchildindex - 1 : mchildindex + 1;
  } else {
  mchildindex = (scrollx + mchildwidth / 2) / mchildwidth;
  }
  mchildindex = math.max(0, math.min(mchildindex, mchildrensize - 1));
  int dx = mchildindex * mchildwidth - scrollx;
  smoothscrollby(dx, 0);
  mvelocitytracker.clear();
  log.d(tag, "index:" + scrolltochildindex + " dx:" + dx);
  break;
 }
 default:
  break;
 }

 mlastx = x;
 mlasty = y;
 return true;
 }

 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
 super.onmeasure(widthmeasurespec, heightmeasurespec);
 int measuredwidth = 0;
 int measuredheight = 0;
 final int childcount = getchildcount();
 measurechildren(widthmeasurespec, heightmeasurespec);

 int widthspacesize = measurespec.getsize(widthmeasurespec);
 int widthspecmode = measurespec.getmode(widthmeasurespec);
 int heightspacesize = measurespec.getsize(heightmeasurespec);
 int heightspecmode = measurespec.getmode(heightmeasurespec);
 if (childcount == 0) {
  setmeasureddimension(0, 0);
 } else if (heightspecmode == measurespec.at_most) {
  final view childview = getchildat(0);
  measuredheight = childview.getmeasuredheight();
  setmeasureddimension(widthspacesize, childview.getmeasuredheight());
 } else if (widthspecmode == measurespec.at_most) {
  final view childview = getchildat(0);
  measuredwidth = childview.getmeasuredwidth() * childcount;
  setmeasureddimension(measuredwidth, heightspacesize);
 } else {
  final view childview = getchildat(0);
  measuredwidth = childview.getmeasuredwidth() * childcount;
  measuredheight = childview.getmeasuredheight();
  setmeasureddimension(measuredwidth, measuredheight);
 }
 }

 @override
 protected void onlayout(boolean changed, int l, int t, int r, int b) {
 log.d(tag, "width:" + getwidth());
 int childleft = 0;
 final int childcount = getchildcount();
 mchildrensize = childcount;

 for (int i = 0; i < childcount; i++) {
  final view childview = getchildat(i);
  if (childview.getvisibility() != view.gone) {
  final int childwidth = childview.getmeasuredwidth();
  mchildwidth = childwidth;
  childview.layout(childleft, 0, childleft + childwidth,
   childview.getmeasuredheight());
  childleft += childwidth;
  }
 }
 }

 private void smoothscrollby(int dx, int dy) {
 mscroller.startscroll(getscrollx(), 0, dx, 0, 500);
 invalidate();
 }

 @override
 public void computescroll() {
 if (mscroller.computescrolloffset()) {
  scrollto(mscroller.getcurrx(), mscroller.getcurry());
  postinvalidate();
 }
 }

 @override
 protected void ondetachedfromwindow() {
 mvelocitytracker.recycle();
 super.ondetachedfromwindow();
 }
}

这个拦截规则也是父容器在滑动过程中水平距离差与垂直距离差相比。

小结

总的来说,滑动冲突的场景可以分为三种,内外部方向不一致、内外部方向一致、嵌套前面两种情况。如何解决,不管多么复杂的滑动冲突,可以进行拆分,根据的一定的规则,第一种情况可根据滑动距离差、速度差和角度差来解决,第二种和第三种情况,可根据业务上找到突破点,业务上一种状态需要响应,切换到另外一种状态时则不响应,根据业务需求得出相应的处理规则,有了处理规则可以进行下一步处理。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。