当前位置: 移动技术网 > 移动技术>移动开发>Android > 浅谈Android View滑动冲突的解决方法

浅谈Android View滑动冲突的解决方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

引言

这一篇文章我们就通过介绍滑动冲突的规则和一个实例来更加深入的学习view的事件分发机制。

1、外部滑动方向和内部滑动方向不一致

考虑这样一种场景,开发中我们经常使用viewpager和fragment配合使用所组成的页面滑动效果,很多主流的应用都会使用这样的效果。在这种效果中,可以使用左右滑动来切换界面,而每一个界面里面往往又都是listview这样的控件。本来这种情况是存在滑动冲突的,只是viewpager内部处理了这种滑动冲突。如果我们不使用viewpager而是使用scrollview,那么滑动冲突就需要我们自己来处理,否者造成的后果就是内外两层只有一层能滑动。

情况1的解决思路

对于第一种情况的解决思路是这样的:当用户左右滑动时,需要让外层的view拦截点击事件。当用户上下滑动时,需要让内部的view拦截点击事件(外层的view不拦截点击事件),这时候我们就可以根据它们的特性来解决滑动冲突。在这里我们可以根据滑动时水平滑动还是垂直滑动来判断谁来拦截点击事件。下面先介绍一种通用的解决滑动冲突的方法。

外部拦截法

外部拦截法是指:点击事件都经过父容器的拦截处理,如果父容器需要处理此事件就进行拦截,否者不拦截交给子view进行处理。这种方法比较符合点击事件的分发机制。外部拦截法需要重写父容器的onintercepttouchevent方法,在内部做相应的拦截即可。这种方法的伪代码如下:

@override
public boolean onintercepttouchevent(motionevent ev) {
  int x=(int)ev.getx();
  int y=(int)ev.gety();
  boolean intercept=false;
  switch (ev.getaction()){
    //按下事件不要拦截,否则后续事件都会给viewgroup处理
    case motionevent.action_down:
      intercept=false;
      break;
    case motionevent.action_move:
      //如果是横向移动就进行拦截,否则不拦截
      int deltax=x-mlastx;
      int deltay=y-mlasty;
      if(父容器需要当前点击事件){
        intercept=true;
      }else {
        intercept=false;
      }
      break;
    case motionevent.action_up:
      intercept=false;
      break;
  }
  mlastx = x;
  mlasty = y;
  return intercept;
}

上面代码是外部拦截法的典型逻辑,针对不同的滑动冲突,只需要修改父容器需要当前点击事件的条件即可,其他均不需要修改。我们在描述下:在onintercepttouchevent方法中,首先是action_down事件,父容器必须返回false,即不拦截action_down事件,这是因为一旦父容器拦截action_down,那么后续的action_move和action_up都会直接交给父容器处理,这时候事件就没法传递给子元素了;其次是action_move事件,这个事件可以根据需要来决定是否需要拦截。

下面来看一个具体的实例,这个实现模拟viewpager的效果,我们定义一个全新的控件,名称叫horizontalscrollview。具体代码如下:

1、我们先看activity中的代码:

public class mainactivity extends activity{

  private horizontalscrollview mlistcontainer;

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);

    initview();
  }

  private void initview() {
    layoutinflater inflater = getlayoutinflater();
    mlistcontainer = (horizontalscrollview) findviewbyid(r.id.container);
    final int screenwidth = myutils.getscreenmetrics(this).widthpixels;
    for (int i = 0; i < 3; i++) {
      viewgroup layout = (viewgroup) inflater.inflate(
          r.layout.content_layout, mlistcontainer, false);
      layout.getlayoutparams().width = screenwidth;
      textview textview = (textview) layout.findviewbyid(r.id.title);
      textview.settext("page " + (i + 1));
      layout.setbackgroundcolor(color.rgb(255 / (i + 1), 255 / (i + 1), 0));
      createlist(layout);
      mlistcontainer.addview(layout);
    }
  }

  private void createlist(viewgroup layout) {
    listview listview = (listview) layout.findviewbyid(r.id.list);
    arraylist<string> datas = new arraylist<>();
    for (int i = 0; i < 50; i++) {
      datas.add("name " + i);
    }

    arrayadapter<string> adapter = new arrayadapter<>(this, r.layout.content_list_item, r.id.name, datas);
    listview.setadapter(adapter);
  }
}

在这个代码中,我们创建了3个listview然后将其添加到我们自定义控件的。这里horizontalscrollview是父容器,listview是子view。下面我们就使用外部拦截法来实现horizontalscrollview,代码如下:

/**
 * 横向布局控件
 * 模拟经典滑动冲突
 * 我们此处使用scrollview来模拟viewpager,那么必须手动处理滑动冲突,否则内外两层只能有一层滑动,那就是滑动冲突。另外内部左右滑动,外部上下滑动也同样属于该类
 */
public class horizontalscrollview extends viewgroup {

  //记录上次滑动的坐标
  private int mlastx = 0;
  private int mlasty = 0;
  private windowmanager wm;
  //子view的个数
  private int mchildcount;
  private int mscreenwidth;
  //自定义控件横向宽度
  private int mmeasurewidth;
  //滑动加载下一个界面的阈值
  private int mcrital;
  //滑动辅助类
  private scroller mscroller;
  //当前展示的子view的索引
  private int showviewindex;

  public horizontalscrollview(context context){
    this(context,null);
  }

  public horizontalscrollview(context context, attributeset attributeset){
    super(context,attributeset);
    init(context);
  }

  /**
   * 初始化
   * @param context
   */
  public void init(context context) {
    //读取屏幕相关的长宽
    wm = ((activity)context).getwindowmanager();
    mscreenwidth = wm.getdefaultdisplay().getwidth();
    mcrital=mscreenwidth/4;
    mscroller=new scroller(context);
    showviewindex=1;
  }

  /**
   * 重新事件拦截机制
   * 我们分析了view的事件分发,我们知道点击事件的分发顺序是 通过父布局分发,如果父布局没有拦截,即onintercepttouchevent返回false,
   * 才会传递给子view。所以我们就可以利用onintercepttouchevent()这个方法来进行事件的拦截。来看一下代码
   * 此处使用外部拦截法
   * @param ev
   * @return
   */
  @override
  public boolean onintercepttouchevent(motionevent ev) {
    int x=(int)ev.getx();
    int y=(int)ev.gety();
    boolean intercept=false;
    switch (ev.getaction()){
      //按下事件不要拦截,否则后续事件都会给viewgroup处理
      case motionevent.action_down:
        intercept=false;
        if(!mscroller.isfinished()){
          mscroller.abortanimation();
          intercept=true;
        }
        break;
      case motionevent.action_move:
        //如果是横向移动就进行拦截,否则不拦截
        int deltax=x-mlastx;
        int deltay=y-mlasty;
        if(math.abs(deltax)>math.abs(deltay)){
          intercept=true;
        }else {
          intercept=false;
        }
        break;
      case motionevent.action_up:
        intercept=false;
        break;
    }
    mlastx = x;
    mlasty = y;
    return intercept;
  }


  @override
  public boolean ontouchevent(motionevent 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;
        /**
         * scrollx是指viewgroup的左侧边框和当前内容左侧边框之间的距离
         */
        int scrollx=getscrollx();
        if(scrollx-deltax>0
            && (scrollx-deltax)<=(mmeasurewidth-mscreenwidth)) {
          scrollby(-deltax, 0);
        }
        break;
      case motionevent.action_up:
        scrollx=getscrollx();
        int dx;
        //计算滑动的差值,如果超过1/4就滑动到下一页
        int subscrollx=scrollx-((showviewindex-1)*mscreenwidth);
        if(math.abs(subscrollx)>=mcrital){
          boolean next=scrollx>(showviewindex-1)*mscreenwidth;
          if(showviewindex<3 && next) {
            showviewindex++;
          }else {
            showviewindex--;
          }
        }
        dx=(showviewindex - 1) * mscreenwidth - scrollx;
        smoothscrollbydx(dx);
        break;
    }
    mlastx = x;
    mlasty = y;
    return true;
  }


  /**
   * 缓慢滚动到指定位置
   * @param dx
   */
  private void smoothscrollbydx(int dx) {
    //在1000毫秒内滑动dx距离,效果就是慢慢滑动
    mscroller.startscroll(getscrollx(), 0, dx, 0, 1000);
    invalidate();
  }

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

从上面代码中,我们看到我们只是很简单的采用横向滑动距离和垂直滑动距离进行比较来判断滑动方向。在滑动过程中,当水平方向的距离大时就判断为水平滑动,否者就是垂直滑动。

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网