当前位置: 移动技术网 > 移动技术>移动开发>Android > Android滑动冲突的完美解决方案

Android滑动冲突的完美解决方案

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

关于滑动冲突

在android开发中,如果是一些简单的布局,都很容易搞定,但是一旦涉及到复杂的页面,特别是为了兼容小屏手机而使用了scrollview以后,就会出现很多点击事件的冲突,最经典的就是scrollview中嵌套了listview。我想大部分刚开始接触android的同学们都踩到过这个坑,下面跟着小编一起来看看解决方案吧。。

同方向滑动冲突

比如scrollview嵌套listview,或者是scrollview嵌套自己

这里先看一张效果图

上图是在购物软件上常见的上拉查看图文详情,关于这中动画效果的实现,其实实现整体的效果,办法是有很多的,网上有很多相关的例子,但是对某些细节的处理不是很清晰,比如,下拉之后显示的部分(例如底部的图文详情)又是一个类scrollview的控件(比如webview)的话,又会产生新的问题。这里就以下拉查看图文详情为背景做一下同方向滑动冲突的分析。

整体思路
这里看下图

多个scrollview嵌套示意图

首先,关于这张图做一些设定:

     1.黑色的框代表手机屏幕

     2.绿色的框代表一个外层的scrollview

     3.两个红色的框代表嵌套在里面的两个类scrollview控件,这里我们就暂时简称为 sup,sdown

好了,接下来就分析一下实现整个流程的过程。

这里必须明确的一点,无论何时,sup和sdown可见的部分始终是手机屏幕的高度。知道了这一点,我们就可以按以下步骤展开

首先,我们确保外部的scrollview不拦截滑动事件,这样sup必然获得此次事件,然后根据其action_move事件,当其为向下滑动且自身滑动距离+屏幕高度=其自身高度 时,即可认为sup滑动到了底部,此时外部scrollview可拦截滑动事件,从而保证整个视图能够继续向下滑动,这个时候底部sdown就显示出来了。

同理,这时候不允许外部scrollview拦截滑动事件,由sdown处理,根据其action_move事件,当其为向上滑动,且自身可滑动距离为0时,就说明sdown已经滑动到了顶部,这时外部scrollview又可以获得拦截滑动事件的权利,从而保证整个视图能够向上继续滑动,此时sup再次显示,又开始新一轮循环拦截。

这样整体的一个流程就可以实现动图中的效果。好了,说完原理,还是看代码。

代码实现

sup实现

public class upscrollview extends scrollview {
 /**
 * 屏幕高度
 */
 private int mscreenheight;
 /**
 * 上一次的坐标
 */
 private float mlasty;
 /**
 * 当前view滑动距离
 */
 private int mscrolly;
 /**
 * 当前view内子控件高度
 */
 private int mchildh;

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

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

 public upscrollview(context context, attributeset attrs, int defstyleattr) {
 super(context, attrs, defstyleattr);
 init(context);

 }

 private void init(context context) {
 windowmanager wm = (windowmanager) context.getsystemservice(context.window_service);
 displaymetrics dm = new displaymetrics();
 wm.getdefaultdisplay().getmetrics(dm);
 mscreenheight = dm.heightpixels;
 }

 @override
 public boolean ontouchevent(motionevent ev) {
 //默认设定顶层view不拦截

 getparent().getparent().requestdisallowintercepttouchevent(true);

 switch (ev.getaction()) {
  case motionevent.action_down:
  mlasty = (int) ev.gety();
  break;
  case motionevent.action_move:
  float y = ev.gety();
  float deltay = y - mlasty;

  mchildh = this.getchildat(0).getmeasuredheight();

  int translatey = mchildh - mscrolly;

  //向上滑动时,如果translatey等于屏幕高度时,即表明滑动到底部,可又顶层view控制滑动
  if (deltay < 0 && translatey == mscreenheight) {
   getparent().getparent().requestdisallowintercepttouchevent(false);
  }
  break;
  default:
  break;

 }

 return super.ontouchevent(ev);
 }

 @override
 protected void onscrollchanged(int l, int t, int oldl, int oldt) {
 super.onscrollchanged(l, t, oldl, oldt);
 mscrolly = t;
 }
}

这里在action_move里做了减法,其实道理是一样的。

onscrollchanged 是在view类中实现,查看其api可以看到其第二个参数t解释

@param t current vertical scroll origin.

即为当前view此次滑动的距离

sdown实现

public class mywebview extends webview {
 public float oldy;
 private int t;

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

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

 public mywebview(context context, attributeset attrs, int defstyleattr) {
 super(context, attrs, defstyleattr);
 init();
 }

 private void init() {
 websettings settings = getsettings();
 settings.setjavascriptenabled(true);
 setwebviewclient(new webviewclient() {
  @override
  public boolean shouldoverrideurlloading(webview view, string url) {
  view.loadurl(url);
  return true;
  }
 });
 }

 @override
 public boolean ontouchevent(motionevent ev) {
 getparent().getparent().requestdisallowintercepttouchevent(true);
 switch (ev.getaction()) {
  case motionevent.action_down:
  oldy = ev.gety();
  break;
  case motionevent.action_move:

  float y = ev.gety();
  float ys = y - oldy;
  if (ys > 0 && t == 0) {
   getparent().getparent().requestdisallowintercepttouchevent(false);
  }
  break;

 }

 return super.ontouchevent(ev);
 }

 @override
 protected void onscrollchanged(int l, int t, int oldl, int oldt) {
 this.t = t;
 super.onscrollchanged(l, t, oldl, oldt);
 }

}

以上看到,这里底部的view并没有继承scrollview,而是选择继承了webview,这里只是为了方便,当然继承scrollview也是没有问题。这里只是需要按实际情况考虑,因为底部图文详情的内容就是一个webview加载数据。

这个类的实现,按照之前说的原理应该很好理解。

外部scrollview

public class customerscrollviews extends scrollview {
 /**
 * 屏幕高度
 */
 private int mscreenheight;

 private upscrollview upscrollview;
 private mywebview mywebview;
 private boolean init = false;

 private float fator = 0.2f;
 private int factorheight;

 private boolean upshow = true;

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

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

 public customerscrollviews(context context, attributeset attrs, int defstyleattr) {
 super(context, attrs, defstyleattr);
 init(context);

 }

 private void init(context context) {
 windowmanager wm = (windowmanager) context.getsystemservice(context.window_service);
 displaymetrics dm = new displaymetrics();
 wm.getdefaultdisplay().getmetrics(dm);
 mscreenheight = dm.heightpixels;
 factorheight = (int) (mscreenheight * fator);
 }

 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
 if (!init) {

  linearlayout parentview = (linearlayout) getchildat(0);
  //获得内部的两个子view
  upscrollview = (upscrollview) parentview.getchildat(0);
  mywebview = (mywebview) parentview.getchildat(2);
//  //并设定其高度为屏幕高度
  upscrollview.getlayoutparams().height = mscreenheight;
  mywebview.getlayoutparams().height = mscreenheight;
  init = true;
 }

 super.onmeasure(widthmeasurespec, heightmeasurespec);
 }

 @override
 protected void onlayout(boolean changed, int l, int t, int r, int b) {
 super.onlayout(changed, l, t, r, b);
 if (changed) {
  scrollto(0, 0);
 }
 }

 @override
 public boolean ontouchevent(motionevent ev) {
 switch (ev.getaction()) {
  case motionevent.action_up:
  int scrolly = getscrolly();
  if (upshow) {
   if (scrolly <= factorheight) {
   smoothscrollto(0, 0);
   } else {
   smoothscrollto(0, mscreenheight);
   upshow = false;

   }
  } else {
   int scrollpadding = mscreenheight - scrolly;
   if (scrollpadding >= factorheight) {
   this.smoothscrollto(0, 0);
   upshow = true;

   } else {
   this.smoothscrollto(0, mscreenheight);
   }

  }

  return true;

 }
 return super.ontouchevent(ev);
 }

}

这个类的实现,就很灵活了,在onmeasure方法中初始化完内部的view之后,在ontouch方法中就可以根据实际需求完成不同的逻辑实现,这里只是为了仿照查看图文详情的效果,对整个视图通过scrollview的smoothscrollto方法进行位移变化,这个逻辑很简单。

这里重点说一下一个地方:

upscrollview = (upscrollview) parentview.getchildat(0);
mywebview = (mywebview) parentview.getchildat(2);

你可能会奇怪中间的child(1)去了哪里?这里还要从mainactivity的布局文件说起

dual_scrollview_activity_layout1.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

 <com.example.dreamwork.activity.superscrollview.customerscrollviews
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 <linearlayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical">

  <com.example.dreamwork.activity.superscrollview.upscrollview

  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:scrollbars="vertical">

  <linearlayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:orientation="vertical">

   <imageview
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:scaletype="fitxy"
   android:src="@drawable/taobao" />
   <imageview
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:scaletype="fitxy"
   android:src="@drawable/taobao" />

   <textview
   android:textsize="20sp"
   android:padding="10dp"
   android:gravity="center"
   android:layout_margintop="20dp"
   android:layout_marginbottom="60dp"
   android:text="查看图文详情"
   android:layout_width="match_parent"
   android:layout_height="wrap_content" />

  </linearlayout>
  </com.example.dreamwork.activity.superscrollview.upscrollview>

  <include layout="@layout/selector_tab_items" />

  <com.example.dreamwork.activity.superscrollview.mywebview
  android:id="@+id/web"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

 </linearlayout>
 </com.example.dreamwork.activity.superscrollview.customerscrollviews>

</linearlayout>

整个布局文件可以看出,我们在customerscrollviews这个最外层的自定义scrollview内部又放置了两个自定义的scrollview(就如我们看到的原理图那样),只不过在这两个scrollview类控件的中间通过layout又放置一个linearlayout,里面的内容就是在动图中看到的那个中间的写着qq,baidu字样的用于切换webview内容的一个view。这里就不贴代码了。

这样,你就可以理解之前的child(1)为什么被跳过了吧。

使用

public class dualscrollviewactivity1 extends activity implements view.onclicklistener {

 private mywebview webview;

 private textview sinatv, qqtv, baidutv;
 private view line1, line2, line3;

 private final string baidu = "http://www.baidu.com";
 private final string qq = "http://www.qq.com";
 private final string sina = "http://sina.cn";

 @override
 protected void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 requestwindowfeature(window.feature_no_title);
 initview();
 sinatv.performclick();
 }

 private void initview() {
 setcontentview(r.layout.dual_scrollview_activity_layout1);
 webview = v.f(this, r.id.web);

 sinatv = v.f(this, r.id.one);
 sinatv.setonclicklistener(this);
 qqtv = v.f(this, r.id.two);
 qqtv.setonclicklistener(this);
 baidutv = v.f(this, r.id.three);
 baidutv.setonclicklistener(this);

 line1 = v.f(this, r.id.line1);
 line2 = v.f(this, r.id.line2);
 line3 = v.f(this, r.id.line3);
 }

 @override
 public void onclick(view v) {
 reset();
 string url = "";
 switch (v.getid()) {
  case r.id.one:
  line1.setvisibility(view.visible);
  url = sina;
  break;
  case r.id.two:
  line2.setvisibility(view.visible);
  url = qq;
  break;
  case r.id.three:
  line3.setvisibility(view.visible);
  url = baidu;
  break;
  default:
  break;
 }

 webview.loadurl(url);
 }

 private void reset(){
 line1.setvisibility(view.gone);
 line2.setvisibility(view.gone);
 line3.setvisibility(view.gone);
 }
}

关于底部view内容更新,webview 通过加载不同url实现不同视图效果,只是作为demo测试,实际中应考虑通过fragment切换实现。

这里对滑动冲突的解决方法,是由内而外的展开,默认使顶层view失去拦截能力,在由底部view的滑动距离,做出不同逻辑判断控制了顶层的拦截与否;这也是比较容易理解和实现的思路。当然,对于此类滑动冲突,有很多不同思路,这里只是列举其一。

实际开发开发中,这种带有同方向滑动特性的控件嵌套时,产生的问题不只是滑动冲突,有时候会有内容显示不全或不显示的情况。

最常见如scrollview嵌套listview,这种情况只需自定义listview使其高度计算为一个很大的值,某种意义上让其失去了滑动的特性,但是这样也让listview貌似失去了视图回收机制,这种时候如果加载很多很多很多图片,效果就会很不理想。对于这种情况,通过对listview添加headview及footview也是一种解决的办法,但也得实际ui情况允许。

scrollview嵌套recyclerview时稍微麻烦一点,需要自定义scrollview,还需要自定义实现linearlayoutmanager。

不同方向滑动冲突

比如scrollview嵌套viewpager,或者是viewpager嵌套scrollview,这种情况其实很典型。现在大部分应用最外层都是viewpager+fragment 的底部切换(比如微信)结构,这种时候,就很容易出现滑动冲突。不过viewpager里面无论是嵌套listview还是scrollview,滑动冲突是没有的,毕竟是官方的东西,可能已经考虑到了这些,所以比较完善。

复杂一点的滑动冲突,基本上就是这两个冲突结合的结果。

滑动冲突解决思路
滑动冲突,就其本质来说,两个不同方向(或者是同方向)的view,其中有一个是占主导地位的,每次总是抢着去处理外界的滑动行为,这样就导致一种很别扭的用户体验,明明只是横向的滑动了一下,纵向的列表却在垂直方向发生了动作。就是说,这个占主导地位的view,每一次都身不由己的拦截了这个滑动的动作,因此,要解决滑动冲突,就是得明确告诉这个占主导地位的view,什么时候你该拦截,什么时候你不应该拦截,应该由下一层的view去处理这个滑动动作。

这里不明白的同学,可以去了解一下android touch事件的分发机制,这也是解决滑动冲突的核心知识。

滑动冲突

这里,说一下背景情况。之前做下拉刷新、上拉加载更多时一直使用的是pulltorefreshview这个控件,因为很方便,不用导入三方工程。在其内部可以放置listview,gridview及scrollview,非常方便,用起来可谓是屡试不爽。但是直到有一天,因项目需要,在listview顶部加了一个轮播图控件bannerview(这个可以参考之前写的一篇学习笔记)。结果发现轮播图滑动的时候,和纵向的下拉刷新组件冲突了。

如之前所说,解决滑动冲突的关键,就是明确告知接收到touch的view,是否需要拦截此次事件。

解决方法

解决方案1,从外部拦截机制考虑

这里,相当于是pulltorefreshview嵌套了viewpager,那么每次优先接收到touch事件的必然是pulltorefreshview。这样就清楚了,看代码:

在pulltorefreshview中:

 @override
 public boolean onintercepttouchevent(motionevent e) {
 int y = (int) e.getrawy();
 int x = (int) e.getrawx();
 boolean resume = false;
 switch (e.getaction()) {
  case motionevent.action_down:
  // 发生down事件时,记录y坐标
  mlastmotiony = y;
  mlastmotionx = x;
  resume = false;
  break;
  case motionevent.action_move:
  // deltay > 0 是向下运动,< 0是向上运动
  int deltay = y - mlastmotiony;
  int deleax = x - mlastmotionx;

  if (math.abs(deleax) > math.abs(deltay)) {
   resume = false;
  } else {
  //当前正处于滑动
   if (isrefreshviewscroll(deltay)) {
   resume = true;
   }
  }
  break;
  case motionevent.action_up:
  case motionevent.action_cancel:
  break;
 }
 return resume;
 }

这里最关键的代码就是这行

if (math.abs(deleax) > math.abs(deltay)) {
   resume = false;
  }

横向滑动距离大于纵向时,无须拦截这次滑动事件。其实,就是这么简单,但前提是你必须明确了解android touch事件的传递机制,期间各个方法执行的顺序及意义。

解决方案2,从内容逆向思维分析

有时候,我们不想去修改引入的第三方控件,或者说是无法修改时。就必须考虑从当前从touch传递事件中最后的那个view逆向考虑。首先,由android中view的touch事件传递机制,我们知道touch事件,首先必然由最外层view拦截,如果无法更改这个最外层view,那么是不是就没辙了呢?其实不然,android这么高大上的系统必然考虑到了这个问题,好了废话不说,先看代码

 private bannerview carouselview;
 private context mcontext;

 private pulltorefreshview refreshview;

 .........

 refreshview.setontouchlistener(new view.ontouchlistener() {
  @override
  public boolean ontouch(view v, motionevent event) {
  carouselview.getparent().requestdisallowintercepttouchevent(false);
  return false;
  }
 });

 carouselview.setontouchlistener(new view.ontouchlistener() {
  @override
  public boolean ontouch(view v, motionevent event) {
  carouselview.getparent().requestdisallowintercepttouchevent(true);
  int x = (int) event.getrawx();
  int y = (int) event.getrawy();

  switch (event.getaction()) {
   case motionevent.action_down:
   lastx = x;
   lasty = y;
   break;
   case motionevent.action_move:
   int deltay = y - lasty;
   int deltax = x - lastx;
   if (math.abs(deltax) < math.abs(deltay)) {
    carouselview.getparent().requestdisallowintercepttouchevent(false);
   } else {
    carouselview.getparent().requestdisallowintercepttouchevent(true);
   }
   default:
   break;
  }
  return false;
  }
 });

首先说一下这个方法

public abstract void requestdisallowintercepttouchevent (boolean disallowintercept)

api里的意思很明确,子view如果不希望其父view拦截touch事件时,可调用此方法。当disallowintercept这个参数为true时,父view将不拦截。

ps:这个方法的命名和其参数的使用逻辑,让我想到了一句很有意思的话,敌人的敌人就是朋友,真不知道google的大神们怎么想的,非要搞一个反逻辑。

言归正传。这里拦截直接也很明确,在carouselview的ontouch方法中每次进入就设定父view不拦截此次事件,然后在motion_move时候,根据滑动的距离判断再决定是父view是否有权利拦截touch事件(即滑动行为)。

总结

好了,本文内容到这基本就结束了,本篇文章只是提供一种解决方法的思路,在具体的场景下,交互往往是贴合具体业务需求的。但是不管怎么样,找出点击事件截断和处理的时机是最重要的,围绕这个关键点,总能找出相应的解决方法。

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

相关文章:

验证码:
移动技术网