修改ViewPager源码使ViewPager支持弹簧效果

来源:互联网 发布:润和软件特色 编辑:程序博客网 时间:2024/05/16 00:53

所谓弹簧效果就是在滑动到ViewPager首页或者末页时继续滑动,随着手的移动ViewPager会继续滑动,但是滑动的距离越来越短.

达到一种好像有弹簧拉着的感觉.如下所示



改的方法很简单

找到ViewPager源码,拷贝一份到你的工程里,然后找到performDrag()方法

    private boolean performDrag(float x) {        boolean needsInvalidate = false;        final float deltaX = mLastMotionX - x;        mLastMotionX = x;        float oldScrollX = getScrollX();        float scrollX = oldScrollX + deltaX;        final int width = getClientWidth();        float leftBound = width * mFirstOffset;        float rightBound = width * mLastOffset;        /*------被替换代码Start-------*///        boolean leftAbsolute = true;//        boolean rightAbsolute = true;////        final ItemInfo firstItem = mItems.get(0);//        final ItemInfo lastItem = mItems.get(mItems.size() - 1);//        if (firstItem.position != 0) {//            leftAbsolute = false;//            leftBound = firstItem.offset * width;//        }//        if (lastItem.position != mAdapter.getCount() - 1) {//            rightAbsolute = false;//            rightBound = lastItem.offset * width;//        }////        if (scrollX < leftBound) {//            if (leftAbsolute) {//                float over = leftBound - scrollX;//                needsInvalidate = mLeftEdge.onPull(Math.abs(over) / width);//            }//            scrollX = leftBound;//        } else if (scrollX > rightBound) {//            if (rightAbsolute) {//                float over = scrollX - rightBound;//                needsInvalidate = mRightEdge.onPull(Math.abs(over) / width);//            }//            scrollX = rightBound;//        }        /*------被替换代码End-------*/        /*------替换代码Start-------*/        if(scrollX < leftBound || scrollX > rightBound){            scrollX = oldScrollX + deltaX;//(阻尼效果实现)        }        /*------替换代码End-------*/        // Don't lose the rounded component        mLastMotionX += scrollX - (int) scrollX;        scrollTo((int) scrollX, getScrollY());        pageScrolled((int) scrollX);        return needsInvalidate;    }

这样就基本达到效果了

但是阻尼的效果并没有实现,现在拉起来还会像普通的翻页一样,没有阻尼感.

增加阻尼效果,需要修改代码中(阻尼效果实现那一行的代码)

根据scrollX leftBound rightBound oldScrollX 配合算法进行运算得到带有阻尼效果的scrollX

在此给出一个简单的实现,没有按照弹簧的性质,只是效果接近

        if(scrollX < leftBound || scrollX > rightBound){            int ratio;            if(scrollX < leftBound)                ratio = (int) (Math.abs(scrollX - leftBound) / 25) + 3;            else                ratio = (int) (Math.abs(scrollX - rightBound) / 25) + 3;            scrollX = oldScrollX + deltaX / ratio;        }




0 0
原创粉丝点击