android 自定义ViewGroup实现仿淘宝的商品详情页

最近公司在新版本上有一个需要, 要在首页添加一个滑动效果, 具体就是仿照X宝的商品详情页, 拉到页面底部时有一个粘滞效果,

 如下图 X东的商品详情页,如果用户继续向上拉的话就进入商品图文描述界面:



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

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

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

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

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


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

[java]  view plain  copy
  1. package com.mcoy.snapscrollview;  
  2.   
  3. import android.content.Context;  
  4. import android.util.AttributeSet;  
  5. import android.util.Log;  
  6. import android.view.MotionEvent;  
  7. import android.view.VelocityTracker;  
  8. import android.view.View;  
  9. import android.view.ViewConfiguration;  
  10. import android.view.ViewGroup;  
  11. import android.widget.Scroller;  
  12.   
  13. /** 
  14.  * @author jiangxinxing---mcoy in English 
  15.  *  
  16.  * 了解此ViewGroup之前, 有两点一定要做到心中有数 
  17.  * 一个是对Scroller的使用, 另一个是对onInterceptTouchEvent和onTouchEvent要做到很熟悉 
  18.  * 以下几个网站可以做参考用 
  19.  * http://blog.csdn.net/bigconvience/article/details/26697645 
  20.  * http://blog.csdn.net/androiddevelop/article/details/8373782 
  21.  * http://blog.csdn.net/xujainxing/article/details/8985063 
  22.  */  
  23. public class McoySnapPageLayout extends ViewGroup {  
  24.       
  25.         。。。。  
  26.       
  27.   
  28.     public interface McoySnapPage {  
  29.         /** 
  30.          * 返回page根节点 
  31.          *  
  32.          * @return 
  33.          */  
  34.         View getRootView();  
  35.   
  36.         /** 
  37.          * 是否滑动到最顶端 
  38.          * 第二页必须自己实现此方法,来判断是否已经滑动到第二页的顶部 
  39.          * 并决定是否要继续滑动到第一页 
  40.          */  
  41.         boolean isAtTop();  
  42.   
  43.         /** 
  44.          * 是否滑动到最底部 
  45.          * 第一页必须自己实现此方法,来判断是否已经滑动到第二页的底部 
  46.          * 并决定是否要继续滑动到第二页 
  47.          */  
  48.         boolean isAtBottom();  
  49.     }  
  50.   
  51.     public interface PageSnapedListener {  
  52.   
  53.         /** 
  54.          * @mcoy 
  55.          * 当从某一页滑动到另一页完成时的回调函数 
  56.          */  
  57.         void onSnapedCompleted(int derection);  
  58.     }  
  59.       
  60.        。。。。。。  
  61.   
  62.     /** 
  63.      * 设置上下页面 
  64.      * @param pageTop 
  65.      * @param pageBottom 
  66.      */  
  67.     public void setSnapPages(McoySnapPage pageTop, McoySnapPage pageBottom) {  
  68.         mPageTop = pageTop;  
  69.         mPageBottom = pageBottom;  
  70.         addPagesAndRefresh();  
  71.     }  
  72.   
  73.     private void addPagesAndRefresh() {  
  74.         // 设置页面id  
  75.         mPageTop.getRootView().setId(0);  
  76.         mPageBottom.getRootView().setId(1);  
  77.         addView(mPageTop.getRootView());  
  78.         addView(mPageBottom.getRootView());  
  79.         postInvalidate();  
  80.     }  
  81.       
  82.     /** 
  83.      * @mcoy add 
  84.      * computeScroll方法会调用postInvalidate()方法, 而postInvalidate()方法中系统 
  85.      * 又会调用computeScroll方法, 因此会一直在循环互相调用, 循环的终结点是在computeScrollOffset() 
  86.      * 当computeScrollOffset这个方法返回false时,说明已经结束滚动。 
  87.      *  
  88.      * 重要:真正的实现此view的滚动是调用scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); 
  89.      */  
  90.     @Override  
  91.     public void computeScroll() {  
  92.         //先判断mScroller滚动是否完成  
  93.         if (mScroller.computeScrollOffset()) {  
  94.             if (mScroller.getCurrY() == (mScroller.getFinalY())) {  
  95.                 if (mNextDataIndex > mDataIndex) {  
  96.                     mFlipDrection = FLIP_DIRECTION_DOWN;  
  97.                     makePageToNext(mNextDataIndex);  
  98.                 } else if (mNextDataIndex < mDataIndex) {  
  99.                     mFlipDrection = FLIP_DIRECTION_UP;  
  100.                     makePageToPrev(mNextDataIndex);  
  101.                 }else{  
  102.                     mFlipDrection = FLIP_DIRECTION_CUR;  
  103.                 }  
  104.                 if(mPageSnapedListener != null){  
  105.                     mPageSnapedListener.onSnapedCompleted(mFlipDrection);  
  106.                 }  
  107.             }  
  108.             //这里调用View的scrollTo()完成实际的滚动  
  109.             scrollTo(mScroller.getCurrX(), mScroller.getCurrY());  
  110.             //必须调用该方法,否则不一定能看到滚动效果  
  111.             postInvalidate();  
  112.         }  
  113.     }  
  114.       
  115.     private void makePageToNext(int dataIndex) {  
  116.         mDataIndex = dataIndex;  
  117.         mCurrentScreen = getCurrentScreen();  
  118.     }  
  119.   
  120.     private void makePageToPrev(int dataIndex) {  
  121.         mDataIndex = dataIndex;  
  122.         mCurrentScreen = getCurrentScreen();  
  123.     }  
  124.       
  125.     public int getCurrentScreen() {  
  126.         for (int i = 0; i < getChildCount(); i++) {  
  127.             if (getChildAt(i).getId() == mDataIndex) {  
  128.                 return i;  
  129.             }  
  130.         }  
  131.         return mCurrentScreen;  
  132.     }  
  133.       
  134.     public View getCurrentView() {  
  135.         for (int i = 0; i < getChildCount(); i++) {  
  136.             if (getChildAt(i).getId() == mDataIndex) {  
  137.                 return getChildAt(i);  
  138.             }  
  139.         }  
  140.         return null;  
  141.     }  
  142.       
  143.     /* 
  144.      * (non-Javadoc) 
  145.      *  
  146.      * @see 
  147.      * android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent) 
  148.      * 重写了父类的onInterceptTouchEvent(),主要功能是在onTouchEvent()方法之前处理 
  149.      * touch事件。包括:down、up、move事件。 
  150.      * 当onInterceptTouchEvent()返回true时进入onTouchEvent()。 
  151.      */  
  152.     @Override  
  153.     public boolean onInterceptTouchEvent(MotionEvent ev) {  
  154.         final int action = ev.getAction();  
  155.         if ((action == MotionEvent.ACTION_MOVE)  
  156.                 && (mTouchState != TOUCH_STATE_REST)) {  
  157.             return true;  
  158.         }  
  159.         final float x = ev.getX();  
  160.         final float y = ev.getY();  
  161.   
  162.         switch (action) {  
  163.         case MotionEvent.ACTION_MOVE:  
  164.             // 记录y与mLastMotionY差值的绝对值。  
  165.             // yDiff大于gapBetweenTopAndBottom时就认为界面拖动了足够大的距离,屏幕就可以移动了。  
  166.             final int yDiff = (int)(y - mLastMotionY);  
  167.             boolean yMoved = Math.abs(yDiff) > gapBetweenTopAndBottom;  
  168.             if (yMoved) {  
  169.                 if(MCOY_DEBUG) {  
  170.                     Log.e(TAG, "yDiff is " + yDiff);  
  171.                     Log.e(TAG, "mPageTop.isFlipToBottom() is " + mPageTop.isAtBottom());  
  172.                     Log.e(TAG, "mCurrentScreen is " + mCurrentScreen);  
  173.                     Log.e(TAG, "mPageBottom.isFlipToTop() is " + mPageBottom.isAtTop());  
  174.                 }  
  175.                 if(yDiff < 0 && mPageTop.isAtBottom() && mCurrentScreen == 0   
  176.                         || yDiff > 0 && mPageBottom.isAtTop() && mCurrentScreen == 1){  
  177.                     Log.e("mcoy""121212121212121212121212");  
  178.                     mTouchState = TOUCH_STATE_SCROLLING;  
  179.                 }  
  180.             }  
  181.             break;  
  182.         case MotionEvent.ACTION_DOWN:  
  183.             // Remember location of down touch  
  184.             mLastMotionY = y;  
  185.             Log.e("mcoy""mScroller.isFinished() is " + mScroller.isFinished());  
  186.             mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST  
  187.                     : TOUCH_STATE_SCROLLING;  
  188.             break;  
  189.         case MotionEvent.ACTION_CANCEL:  
  190.         case MotionEvent.ACTION_UP:  
  191.             // Release the drag  
  192.             mTouchState = TOUCH_STATE_REST;  
  193.             break;  
  194.         }  
  195.         boolean intercept = mTouchState != TOUCH_STATE_REST;  
  196.         Log.e("mcoy""McoySnapPageLayout---onInterceptTouchEvent return " + intercept);  
  197.         return intercept;  
  198.     }  
  199.       
  200.     /* 
  201.      * (non-Javadoc) 
  202.      *  
  203.      * @see android.view.View#onTouchEvent(android.view.MotionEvent) 
  204.      * 主要功能是处理onInterceptTouchEvent()返回值为true时传递过来的touch事件 
  205.      */  
  206.     @Override  
  207.     public boolean onTouchEvent(MotionEvent ev) {  
  208.         Log.e("mcoy""onTouchEvent--" + System.currentTimeMillis());  
  209.         if (mVelocityTracker == null) {  
  210.             mVelocityTracker = VelocityTracker.obtain();  
  211.         }  
  212.         mVelocityTracker.addMovement(ev);  
  213.           
  214.         final int action = ev.getAction();  
  215.         final float x = ev.getX();  
  216.         final float y = ev.getY();  
  217.         switch (action) {  
  218.         case MotionEvent.ACTION_DOWN:  
  219.             if (!mScroller.isFinished()) {  
  220.                 mScroller.abortAnimation();  
  221.             }  
  222.             break;  
  223.         case MotionEvent.ACTION_MOVE:  
  224.             if(mTouchState != TOUCH_STATE_SCROLLING){  
  225.                  // 记录y与mLastMotionY差值的绝对值。  
  226.                  // yDiff大于gapBetweenTopAndBottom时就认为界面拖动了足够大的距离,屏幕就可以移动了。  
  227.                 final int yDiff = (int) Math.abs(y - mLastMotionY);  
  228.                 boolean yMoved = yDiff > gapBetweenTopAndBottom;  
  229.                 if (yMoved) {  
  230.                     mTouchState = TOUCH_STATE_SCROLLING;  
  231.                 }  
  232.             }  
  233.             // 手指拖动屏幕的处理  
  234.             if ((mTouchState == TOUCH_STATE_SCROLLING)) {  
  235.                 // Scroll to follow the motion event  
  236.                 final int deltaY = (int) (mLastMotionY - y);  
  237.                 mLastMotionY = y;  
  238.                 final int scrollY = getScrollY();  
  239.                 if(mCurrentScreen == 0){//显示第一页,只能上拉时使用  
  240.                     if(mPageTop != null && mPageTop.isAtBottom()){  
  241.                         scrollBy(0, Math.max(-1 * scrollY, deltaY));  
  242.                     }  
  243.                 }else{  
  244.                     if(mPageBottom != null && mPageBottom.isAtTop()){  
  245.                          scrollBy(0, deltaY);  
  246.                     }  
  247.                 }  
  248.             }  
  249.             break;  
  250.         case MotionEvent.ACTION_CANCEL:  
  251.         case MotionEvent.ACTION_UP:  
  252.             // 弹起手指后,切换屏幕的处理  
  253.             if (mTouchState == TOUCH_STATE_SCROLLING) {  
  254.                 final VelocityTracker velocityTracker = mVelocityTracker;  
  255.                 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);  
  256.                 int velocityY = (int) velocityTracker.getYVelocity();  
  257.                 if (Math.abs(velocityY) > SNAP_VELOCITY) {  
  258.                     if( velocityY > 0 && mCurrentScreen == 1 && mPageBottom.isAtTop()){  
  259.                         snapToScreen(mDataIndex-1);  
  260.                     }else if(velocityY < 0  && mCurrentScreen == 0){  
  261.                         snapToScreen(mDataIndex+1);  
  262.                     }else{  
  263.                         snapToScreen(mDataIndex);  
  264.                     }  
  265.                 } else {  
  266.                     snapToDestination();  
  267.                 }  
  268.                 if (mVelocityTracker != null) {  
  269.                     mVelocityTracker.recycle();  
  270.                     mVelocityTracker = null;  
  271.                 }  
  272.             }else{  
  273.             }  
  274.             mTouchState = TOUCH_STATE_REST;  
  275.             break;  
  276.           
  277.         default:  
  278.             break;  
  279.         }  
  280.         return true;  
  281.     }  
  282.       
  283.     private void clearOnTouchEvents(){  
  284.         mTouchState = TOUCH_STATE_REST;  
  285.          if (mVelocityTracker != null) {  
  286.              mVelocityTracker.recycle();  
  287.              mVelocityTracker = null;  
  288.          }  
  289.     }  
  290.   
  291.     private void snapToDestination() {  
  292.         // 计算应该去哪个屏  
  293.         final int flipHeight = getHeight() / 8;  
  294.           
  295.         int whichScreen = -1;  
  296.         final int topEdge = getCurrentView().getTop();  
  297.   
  298.         if(topEdge < getScrollY() && (getScrollY()-topEdge) >= flipHeight && mCurrentScreen == 0){  
  299.             //向下滑动      
  300.             whichScreen = mDataIndex + 1;  
  301.         }else if(topEdge > getScrollY() && (topEdge - getScrollY()) >= flipHeight && mCurrentScreen == 1){  
  302.             //向上滑动  
  303.             whichScreen = mDataIndex - 1;  
  304.         }else{  
  305.             whichScreen = mDataIndex;  
  306.         }  
  307.         Log.e(TAG, "snapToDestination mDataIndex = " + mDataIndex);  
  308.         Log.e(TAG, "snapToDestination whichScreen = " + whichScreen);  
  309.         snapToScreen(whichScreen);  
  310.     }  
  311.       
  312.     private void snapToScreen(int dataIndex) {  
  313.         if (!mScroller.isFinished())  
  314.             return;  
  315.          
  316.         final int direction = dataIndex - mDataIndex;  
  317.         mNextDataIndex = dataIndex;  
  318.         boolean changingScreens = dataIndex != mDataIndex;  
  319.         View focusedChild = getFocusedChild();  
  320.         if (focusedChild != null && changingScreens) {  
  321.             focusedChild.clearFocus();  
  322.         }  
  323.         //在这里判断是否已到目标位置~  
  324.         int newY = 0;  
  325.         switch (direction) {  
  326.         case 1:  //需要滑动到第二页  
  327.             Log.e(TAG, "the direction is 1");  
  328.             newY = getCurrentView().getBottom(); // 最终停留的位置  
  329.             break;  
  330.         case -1:  //需要滑动到第一页  
  331.             Log.e(TAG, "the direction is -1");  
  332.             Log.e(TAG, "getCurrentView().getTop() is "  
  333.                     + getCurrentView().getTop() + " getHeight() is "  
  334.                     + getHeight());  
  335.             newY = getCurrentView().getTop() - getHeight(); // 最终停留的位置  
  336.             break;  
  337.         case 0:  //滑动距离不够, 因此不造成换页,回到滑动之前的位置  
  338.             Log.e(TAG, "the direction is 0");  
  339.             newY = getCurrentView().getTop(); //第一页的top是0, 第二页的top应该是第一页的高度  
  340.             break;  
  341.         default:  
  342.             break;  
  343.         }  
  344.         final int cy = getScrollY(); // 启动的位置  
  345.         Log.e(TAG, "the newY is " + newY + " cy is " + cy);  
  346.         final int delta = newY - cy; // 滑动的距离,正值是往左滑<—,负值是往右滑—>  
  347.         mScroller.startScroll(0, cy, 0, delta, Math.abs(delta));  
  348.         invalidate();  
  349.     }  
  350.       
  351.      
  352.   
  353. }  

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

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


Demo地址: http://download.csdn.net/detail/zxm317122667/8926295

转自:http://blog.csdn.net/zxm317122667/article/details/47018357

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值