public interface PageTransformer { /** * Apply a property transformation to the given page. * * @param page Apply the transformation to this page * @param position Position of page relative to the current front-and-center * position of the pager. 0 is front and center. 1 is one full * page position to the right, and -1 is one page position to the left. */ void transformPage(@NonNull View page, float position); }
position 指的是该内容页的位置偏移,该偏移是相对的,具体表示请看一张图,页面静止时,以屏幕左边界为 0,屏幕内的页面 position 为0,左边为-1,依次递减,右侧为1,依次递增。当屏幕滑动时,page2只出现一半,此时,page2 的 position 为-0.5,page3 为0.5,依次类推可得出其他page 回调的 position 值
其实这个原理很简单,在每一次滚动的时候,在 ViewPager 内部,计算出 每一个view 的 position ,并且调用这个接口的方法就可以实现了
源码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
protected void onPageScrolled(int position, float offset, int offsetPixels) { // 省略....... if (mPageTransformer != null) { final int scrollX = getScrollX(); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.isDecor) continue; final float transformPos = (float) (child.getLeft() - scrollX) / getClientWidth(); mPageTransformer.transformPage(child, transformPos); } } // .... }