概览
垂直方向的viewpager,拍拍,淘宝详情垂直滑动的切换Demo
================ 2014-11-24 =================
1、对VerticalViewPager进行扩展
2、修复部分机型不兼容
3、剔除高级版本api,兼容低版本
4、提供容器组件
================ 2014-11-24 ====================
git地址:https://github.com/landsnail/VerticalViewPager
作者主要是对开源VerticalViewPager的基础上,进行一些兼容的改写和丰富组件的扩展工作。
提供了滑动的ScrollView,ListView,WebView的滑动方案。以及向低版本兼容工作。
关键原理:
判断组件滑动的位置,如果滑到顶部或者末端,则改变事件流方向,直接传递给此刻受理者。本文直接传递给VerticalViewPage。(见:getParent函数)
1、WebView和ListView改写的核心代码:
/**
* @param direction -1 页面从上往下走。
* @return
*/
public boolean canScrollVertical(int direction) {
final int offset = computeVerticalScrollOffset();
final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
if (range == 0) return false;
else return (direction < 0) ? (offset > 0) : (offset < range - 1);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev);
}
float mLastMotionY = 0;
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastMotionY = event.getY();
getParent().getParent().getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE: {
float direction = mLastMotionY - event.getY();
mLastMotionY = event.getY();
Log.i("msg", "scroll" + getScrollY() + " direction:" + direction);
if ((getScrollY() == 0 && direction < -5)) {
Log.i("msg", "offset===========");
//获得VerticalViewPager的实例
getParent().getParent().getParent().requestDisallowInterceptTouchEvent(false);
((View) getParent().getParent().getParent()).onTouchEvent(event);
} else {
getParent().getParent().getParent().requestDisallowInterceptTouchEvent(true);
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
getParent().getParent().getParent().requestDisallowInterceptTouchEvent(false);
break;
}
return super.dispatchTouchEvent(event);
}
2、ScrollView改写的核心代码:
float mLastMotionX = 0;
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
// getParent().requestDisallowInterceptTouchEvent(false);
final float x = ((MotionEvent) event).getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastMotionX = x;
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE: {
if ((getChildAt(0).getMeasuredHeight() <= (getScrollY() + getHeight()))) {
Log.i("msg", "offset---------" + getParent().toString());
getParent().requestDisallowInterceptTouchEvent(false);
//获得 VerticalViewPager 的实例
((View) getParent()).onTouchEvent(event);
} else {
getParent().requestDisallowInterceptTouchEvent(true);
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
getParent().requestDisallowInterceptTouchEvent(false);
break;
}
try {
return super.dispatchTouchEvent(event);
}catch (Exception ex){
Log.d("dispatchTouchEvent Exception:", ex.getLocalizedMessage());
return false;
}
}
更多的代码,请前往git开源地址下载查看,如有问题,望不吝赐教。