当前位置: 移动技术网 > 移动技术>移动开发>Android > Android自定义ViewGroup实现淘宝商品详情页

Android自定义ViewGroup实现淘宝商品详情页

2019年08月01日  | 移动技术网移动技术  | 我要评论

最近公司在新版本上有一个需要,要在首页添加一个滑动效果,具体就是仿照x宝的商品详情页,拉到页面底部时有一个粘滞效果,如下图x东的商品详情页,如果用户继续向上拉的话就进入商品图文描述界面:

刚开始是想拿来主义,直接从网上找个现成的demo来用, 但是网上无一例外的答案都特别统一: 几乎全部是scrollview中再套两个scrollview,或者是一个linearlayout中套两个scrollview。 通过指定父view和子view的focus来切换滑动的处理界面---即通过view的requestdisallowintercepttouchevent方法来决定是哪一个scrollview来处理滑动事件。

使用以上方法虽然可以解一时之渴, 但是存在几点缺陷:

1  扩展性不强 : 如果后续产品要求不止是两页滑动呢,是三页滑动呢, 难道要嵌3个scrollview并通过n个判断来实现吗

2  兼容性不强 : 如果需要在某一个子页中需要处理左右滑动事件或者双指操作事件呢, 此方法就无法实现了

3 个人原因 : 个人喜欢自己掌握主动性,事件的处理自己来控制更靠谱一些(ps:就如同一份感情一样,需要细心去经营)

总和以上原因, 自己实现了一个viewgroup,实现文章开头提到的效果, 废话不多说  直接上源码,以下只是部分主要源码,并对每一个方法都做了注释,可以参照注释理解。   文章最后对这个viewgroup加了一点实现的细节以及如何使用此viewgroup, 以及demo地址

package com.mcoy.snapscrollview;
 
import android.content.context;
import android.util.attributeset;
import android.util.log;
import android.view.motionevent;
import android.view.velocitytracker;
import android.view.view;
import android.view.viewconfiguration;
import android.view.viewgroup;
import android.widget.scroller;
 
/**
 * @author jiangxinxing---mcoy in english
 * 
 * 了解此viewgroup之前, 有两点一定要做到心中有数
 * 一个是对scroller的使用, 另一个是对onintercepttouchevent和ontouchevent要做到很熟悉
 * 以下几个网站可以做参考用
 * http://blog.csdn.net/bigconvience/article/details/26697645
 * http://blog.csdn.net/androiddevelop/article/details/8373782
 * http://blog.csdn.net/xujainxing/article/details/8985063
 */
public class mcoysnappagelayout extends viewgroup {
 
  。。。。
 
 
 public interface mcoysnappage {
 /**
 * 返回page根节点
 * 
 * @return
 */
 view getrootview();
 
 /**
 * 是否滑动到最顶端
 * 第二页必须自己实现此方法,来判断是否已经滑动到第二页的顶部
 * 并决定是否要继续滑动到第一页
 */
 boolean isattop();
 
 /**
 * 是否滑动到最底部
 * 第一页必须自己实现此方法,来判断是否已经滑动到第二页的底部
 * 并决定是否要继续滑动到第二页
 */
 boolean isatbottom();
 }
 
 public interface pagesnapedlistener {
 
 /**
 * @mcoy
 * 当从某一页滑动到另一页完成时的回调函数
 */
 void onsnapedcompleted(int derection);
 }
 
  。。。。。。
 
 /**
 * 设置上下页面
 * @param pagetop
 * @param pagebottom
 */
 public void setsnappages(mcoysnappage pagetop, mcoysnappage pagebottom) {
 mpagetop = pagetop;
 mpagebottom = pagebottom;
 addpagesandrefresh();
 }
 
 private void addpagesandrefresh() {
 // 设置页面id
 mpagetop.getrootview().setid(0);
 mpagebottom.getrootview().setid(1);
 addview(mpagetop.getrootview());
 addview(mpagebottom.getrootview());
 postinvalidate();
 }
 
 /**
 * @mcoy add
 * computescroll方法会调用postinvalidate()方法, 而postinvalidate()方法中系统
 * 又会调用computescroll方法, 因此会一直在循环互相调用, 循环的终结点是在computescrolloffset()
 * 当computescrolloffset这个方法返回false时,说明已经结束滚动。
 * 
 * 重要:真正的实现此view的滚动是调用scrollto(mscroller.getcurrx(), mscroller.getcurry());
 */
 @override
 public void computescroll() {
 //先判断mscroller滚动是否完成
 if (mscroller.computescrolloffset()) {
 if (mscroller.getcurry() == (mscroller.getfinaly())) {
 if (mnextdataindex > mdataindex) {
  mflipdrection = flip_direction_down;
  makepagetonext(mnextdataindex);
 } else if (mnextdataindex < mdataindex) {
  mflipdrection = flip_direction_up;
  makepagetoprev(mnextdataindex);
 }else{
  mflipdrection = flip_direction_cur;
 }
 if(mpagesnapedlistener != null){
  mpagesnapedlistener.onsnapedcompleted(mflipdrection);
 }
 }
 //这里调用view的scrollto()完成实际的滚动
 scrollto(mscroller.getcurrx(), mscroller.getcurry());
 //必须调用该方法,否则不一定能看到滚动效果
 postinvalidate();
 }
 }
 
 private void makepagetonext(int dataindex) {
 mdataindex = dataindex;
  mcurrentscreen = getcurrentscreen();
 }
 
 private void makepagetoprev(int dataindex) {
 mdataindex = dataindex;
  mcurrentscreen = getcurrentscreen();
 }
 
 public int getcurrentscreen() {
 for (int i = 0; i < getchildcount(); i++) {
 if (getchildat(i).getid() == mdataindex) {
 return i;
 }
 }
 return mcurrentscreen;
 }
 
 public view getcurrentview() {
 for (int i = 0; i < getchildcount(); i++) {
 if (getchildat(i).getid() == mdataindex) {
 return getchildat(i);
 }
 }
 return null;
 }
 
 /*
 * (non-javadoc)
 * 
 * @see
 * android.view.viewgroup#onintercepttouchevent(android.view.motionevent)
 * 重写了父类的onintercepttouchevent(),主要功能是在ontouchevent()方法之前处理
 * touch事件。包括:down、up、move事件。
 * 当onintercepttouchevent()返回true时进入ontouchevent()。
 */
 @override
 public boolean onintercepttouchevent(motionevent ev) {
 final int action = ev.getaction();
 if ((action == motionevent.action_move)
 && (mtouchstate != touch_state_rest)) {
 return true;
 }
 final float x = ev.getx();
 final float y = ev.gety();
 
 switch (action) {
 case motionevent.action_move:
 // 记录y与mlastmotiony差值的绝对值。
   // ydiff大于gapbetweentopandbottom时就认为界面拖动了足够大的距离,屏幕就可以移动了。
 final int ydiff = (int)(y - mlastmotiony);
 boolean ymoved = math.abs(ydiff) > gapbetweentopandbottom;
 if (ymoved) {
 if(mcoy_debug) {
  log.e(tag, "ydiff is " + ydiff);
  log.e(tag, "mpagetop.isfliptobottom() is " + mpagetop.isatbottom());
  log.e(tag, "mcurrentscreen is " + mcurrentscreen);
  log.e(tag, "mpagebottom.isfliptotop() is " + mpagebottom.isattop());
 }
 if(ydiff < 0 && mpagetop.isatbottom() && mcurrentscreen == 0 
  || ydiff > 0 && mpagebottom.isattop() && mcurrentscreen == 1){
  log.e("mcoy", "121212121212121212121212");
  mtouchstate = touch_state_scrolling;
 }
 }
 break;
 case motionevent.action_down:
 // remember location of down touch
 mlastmotiony = y;
 log.e("mcoy", "mscroller.isfinished() is " + mscroller.isfinished());
 mtouchstate = mscroller.isfinished() ? touch_state_rest
  : touch_state_scrolling;
 break;
 case motionevent.action_cancel:
 case motionevent.action_up:
 // release the drag
 mtouchstate = touch_state_rest;
 break;
 }
 boolean intercept = mtouchstate != touch_state_rest;
 log.e("mcoy", "mcoysnappagelayout---onintercepttouchevent return " + intercept);
 return intercept;
 }
 
 /*
 * (non-javadoc)
 * 
 * @see android.view.view#ontouchevent(android.view.motionevent)
 * 主要功能是处理onintercepttouchevent()返回值为true时传递过来的touch事件
 */
 @override
 public boolean ontouchevent(motionevent ev) {
 log.e("mcoy", "ontouchevent--" + system.currenttimemillis());
  if (mvelocitytracker == null) {
   mvelocitytracker = velocitytracker.obtain();
  }
  mvelocitytracker.addmovement(ev);
  
 final int action = ev.getaction();
 final float x = ev.getx();
 final float y = ev.gety();
 switch (action) {
 case motionevent.action_down:
 if (!mscroller.isfinished()) {
 mscroller.abortanimation();
 }
 break;
 case motionevent.action_move:
  if(mtouchstate != touch_state_scrolling){
     // 记录y与mlastmotiony差值的绝对值。
     // ydiff大于gapbetweentopandbottom时就认为界面拖动了足够大的距离,屏幕就可以移动了。
    final int ydiff = (int) math.abs(y - mlastmotiony);
    boolean ymoved = ydiff > gapbetweentopandbottom;
    if (ymoved) {
     mtouchstate = touch_state_scrolling;
    }
   }
   // 手指拖动屏幕的处理
   if ((mtouchstate == touch_state_scrolling)) {
    // scroll to follow the motion event
    final int deltay = (int) (mlastmotiony - y);
    mlastmotiony = y;
    final int scrolly = getscrolly();
    if(mcurrentscreen == 0){//显示第一页,只能上拉时使用
     if(mpagetop != null && mpagetop.isatbottom()){
     scrollby(0, math.max(-1 * scrolly, deltay));
     }
    }else{
     if(mpagebottom != null && mpagebottom.isattop()){
     scrollby(0, deltay);
     }
    }
   }
 break;
 case motionevent.action_cancel:
 case motionevent.action_up:
 // 弹起手指后,切换屏幕的处理
 if (mtouchstate == touch_state_scrolling) {
  final velocitytracker velocitytracker = mvelocitytracker;
    velocitytracker.computecurrentvelocity(1000, mmaximumvelocity);
    int velocityy = (int) velocitytracker.getyvelocity();
    if (math.abs(velocityy) > snap_velocity) {
     if( velocityy > 0 && mcurrentscreen == 1 && mpagebottom.isattop()){
      snaptoscreen(mdataindex-1);
     }else if(velocityy < 0 && mcurrentscreen == 0){
      snaptoscreen(mdataindex+1);
     }else{
      snaptoscreen(mdataindex);
     }
    } else {
     snaptodestination();
    }
    if (mvelocitytracker != null) {
     mvelocitytracker.recycle();
     mvelocitytracker = null;
    }
 }else{
 }
 mtouchstate = touch_state_rest;
 break;
 
 default:
 break;
 }
 return true;
 }
 
 private void clearontouchevents(){
 mtouchstate = touch_state_rest;
 if (mvelocitytracker != null) {
    mvelocitytracker.recycle();
    mvelocitytracker = null;
   }
 }
 
 private void snaptodestination() {
 // 计算应该去哪个屏
 final int flipheight = getheight() / 8;
  
  int whichscreen = -1;
  final int topedge = getcurrentview().gettop();
 
  if(topedge < getscrolly() && (getscrolly()-topedge) >= flipheight && mcurrentscreen == 0){
   //向下滑动 
   whichscreen = mdataindex + 1;
  }else if(topedge > getscrolly() && (topedge - getscrolly()) >= flipheight && mcurrentscreen == 1){
   //向上滑动
   whichscreen = mdataindex - 1;
  }else{
   whichscreen = mdataindex;
  }
  log.e(tag, "snaptodestination mdataindex = " + mdataindex);
  log.e(tag, "snaptodestination whichscreen = " + whichscreen);
  snaptoscreen(whichscreen);
 }
 
 private void snaptoscreen(int dataindex) {
  if (!mscroller.isfinished())
   return;
  
  final int direction = dataindex - mdataindex;
  mnextdataindex = dataindex;
  boolean changingscreens = dataindex != mdataindex;
  view focusedchild = getfocusedchild();
  if (focusedchild != null && changingscreens) {
   focusedchild.clearfocus();
  }
  //在这里判断是否已到目标位置~
  int newy = 0;
 switch (direction) {
 case 1: //需要滑动到第二页
 log.e(tag, "the direction is 1");
 newy = getcurrentview().getbottom(); // 最终停留的位置
 break;
 case -1: //需要滑动到第一页
 log.e(tag, "the direction is -1");
 log.e(tag, "getcurrentview().gettop() is "
  + getcurrentview().gettop() + " getheight() is "
  + getheight());
 newy = getcurrentview().gettop() - getheight(); // 最终停留的位置
 break;
 case 0: //滑动距离不够, 因此不造成换页,回到滑动之前的位置
 log.e(tag, "the direction is 0");
 newy = getcurrentview().gettop(); //第一页的top是0, 第二页的top应该是第一页的高度
 break;
 default:
 break;
 }
  final int cy = getscrolly(); // 启动的位置
  log.e(tag, "the newy is " + newy + " cy is " + cy);
  final int delta = newy - cy; // 滑动的距离,正值是往左滑<—,负值是往右滑—>
  mscroller.startscroll(0, cy, 0, delta, math.abs(delta));
  invalidate();
 }
 

 
}

mcoysnappage是定义在viewgroup的一个接口, 比如说我们需要类似某东商品详情那样,有上下两页的效果。 那我就需要自己定义两个类实现这个接口,并实现接口的方法。getrootview需要返回当前页需要显示的布局内容;isattop需要返回当前页是否已经在顶端; isatbottom需要返回当前页是否已经在底部

onintercepttoucheventontouchevent决定当前的滑动状态, 并决定是有当前viewgroup拦截touch事件还是由子view去消费touch事件

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

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

相关文章:

验证码:
移动技术网