和你想的一样,我们覆写了onStartNestedScroll和onNestedPreScroll方法,但是除了这两个方法外,我们还覆写了onNestedPreFling方法,这个方法是干嘛的? 估计大家已经猜出来了,这里是处理fling动作的,你想想,我们在滑动松开手的时候,ScrollView是不是还继续滑动一会,那我们也需要让跟随的那个ScrollView也要继续滑动一会,这种效果,onNestedPreFling就派上用场了。
好,接下来我们来实现代码,首先来看看onStartNestedScroll,这里的返回值表明这次滑动我们要不要关心,我们要关心什么样的滑动?当然是y轴方向上的。
(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) { return (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0; }现在我们准备好了关心的滑动事件了,那如何让它滑动起来呢?还是要看onNestedPreScroll的实现
(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed) { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed); int leftScrolled = target.getScrollY(); child.setScrollY(leftScrolled); }也很简单,让child的scrollY的值等于目标的scrollY的值就ok啦,那fling呢?更简单,
(CoordinatorLayout coordinatorLayout, View child, View target, float velocityX, float velocityY, boolean consumed) { ((NestedScrollView) child).fling((int)velocityY); return true; }直接将现在的y轴上的速度传递传递给child,让他fling起来就ok了。
定义好了Behavior,就得在xml中使用了,使用方法和前面的一样。