SwipeRefreshLayout 是Android Support Library, revision 19.1.0添加support v4库中的一个下拉刷新控件,关于android的下拉刷新框架现在有好多,曾经用过XListView,现在工作中基本上无需用到下拉刷新的功能。废话不多说了,这里来记录一下android自带的刷新控件SwipeRefreshLayout的使用,借此顺便来熟悉一下android 在Lollipop版本推出的嵌套滑动机制(NestedScrolling)。

首先来看SwipeRefreshLayout的使用,使用很简单,看一下布局文件

<?xml version="1.0" encoding="utf-8"?>    
注意 SwipeRefreshLayout只能有一个直接的子View。这里用了RecyclerView,因为前面刚刚讲过它。其实用啥子View都行,只要你想通过竖直方向的滑动来刷新该View的显示内容。

关于SwipeRefreshLayout的一些API:

swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);        swipeRefreshLayout.setSize(SwipeRefreshLayout.LARGE);        //swipeRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);//默认  设置进度圈的大小,只有两个值:DEFAULT、LARGE        //swipeRefreshLayout.setProgressBackgroundColorSchemeColor(Color.RED);//设置进度圈的背景色。        //swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimaryDark,R.color.colorPrimary,R.color.cardViewcolor);//设置进度动画的颜色      .....        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {            @Override            public void onRefresh() {                Log.d("test","onRefresh");                datas.add(0,new Contact("xiaochen","10086"));                handler.postDelayed(new Runnable() {                    @Override                    public void run() {                        mAdapter.notifyDataSetChanged();                        swipeRefreshLayout.setRefreshing(false);//设置刷新状态 false停止刷新                    }                },5000);            }        });

这里还是根据前文的demo来写的,就刷新的时候,在第一个位置添加一条数据,咱看效果:



SwipeRefreshLayout的使用没啥好讲的,比较简单。

咱再一张效果图:



注意上面我就传一个事件流,即一个down事件,N个Move事件,一个up事件,然而我们可以发现Move事件的时候被SwipeRefreshLayout(出现进度圈)和RecyclerView(向上滚动)都处理了,记得前面源码分析Android触摸事件处理机制一文我们分析过,android默认的触摸事件处理框架一个事件流只能被一个View处理,当然通过一些手段还是可以做到一个事件流同时被几个View处理,显然SwipeRefreshLayout和RecyclerView对触摸事件的处理流程做了一定处理。

所以咱来看看SwipeRefreshLayout和RecyclerView的 源码,这里就不是去分析它们源码看它们怎么处理事件,只是引出嵌套滑动的机制:

public class SwipeRefreshLayout extends ViewGroup implements NestedScrollingParent,        NestedScrollingChild {


 private final NestedScrollingParentHelper mNestedScrollingParentHelper;    private final NestedScrollingChildHelper mNestedScrollingChildHelper;
SwipeRefreshLayout实现了NestedScrollingParent接口,同时它也有一个成员变量是NestedScrollingParentHelper类型

public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild {

 private NestedScrollingChildHelper mScrollingChildHelper;

RecyclerView实现了 NestedScrollingChild接口,同时它也有一个成员变量是NestedScrollingChildHelper类型
发现了四个新的对象NestedScrollingParent,NestedScrollingChild,NestedScrollingChildHelper,NestedScrollingParentHelper。

前面说嵌套滑动机制主要由上面四个对象来实现的,SwipeRefreshLayout和RecyclerView之间就是利用嵌套滑动来实现下拉刷新的,大家有兴趣可以阅读源码去分析。下面讲一下android这个嵌套滑动机制

Android 在发布 Lollipop版本之后,为了更好的用户体验,Google为Android的滑动机制提供了NestedScrolling特性

理解嵌套滑动, 需要理解以下几个类(接口): NestedScrollingChild NestedScrollingParent NestedScrollingChildHelper NestedScrollingParentHelper 以上四个类都在 support-v4 包(Android Support Library, revision 22.1.0添加的)中提供,Lollipop的View默认实现了几种方法。

先来看  NestedScrollingChild 接口,  顾名思义, 这个是子View 应该实现 的接口:

/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package android.support.v4.view;import android.view.MotionEvent;import android.view.VelocityTracker;import android.view.View;import android.view.ViewConfiguration;import android.view.ViewParent;/** * This interface should be implemented by {@link android.view.View View} subclasses that wish * to support dispatching nested scrolling operations to a cooperating parent * {@link android.view.ViewGroup ViewGroup}. * * 

Classes implementing this interface should create a final instance of a * {@link NestedScrollingChildHelper} as a field and delegate any View methods to the * NestedScrollingChildHelper methods of the same signature.

* *

Views invoking nested scrolling functionality should always do so from the relevant * {@link ViewCompat}, {@link ViewGroupCompat} or {@link ViewParentCompat} compatibility * shim static methods. This ensures interoperability with nested scrolling views on Android * 5.0 Lollipop and newer.

*/public interface NestedScrollingChild { /** * Enable or disable nested scrolling for this view. * *

If this property is set to true the view will be permitted to initiate nested * scrolling operations with a compatible parent view in the current hierarchy. If this * view does not implement nested scrolling this will have no effect. Disabling nested scrolling * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} * the nested scroll.

* * @param enabled true to enable nested scrolling, false to disable * * @see #isNestedScrollingEnabled() */ public void setNestedScrollingEnabled(boolean enabled); /** * Returns true if nested scrolling is enabled for this view. * *

If nested scrolling is enabled and this View class implementation supports it, * this view will act as a nested scrolling child view when applicable, forwarding data * about the scroll operation in progress to a compatible and cooperating nested scrolling * parent.

* * @return true if nested scrolling is enabled * * @see #setNestedScrollingEnabled(boolean) */ public boolean isNestedScrollingEnabled(); /** * Begin a nestable scroll operation along the given axes. * *

A view starting a nested scroll promises to abide by the following contract:

* *

The view will call startNestedScroll upon initiating a scroll operation. In the case * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. * In the case of touch scrolling the nested scroll will be terminated automatically in * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. * In the event of programmatic scrolling the caller must explicitly call * {@link #stopNestedScroll()} to indicate the end of the nested scroll.

* *

If startNestedScroll returns true, a cooperative parent was found. * If it returns false the caller may ignore the rest of this contract until the next scroll. * Calling startNestedScroll while a nested scroll is already in progress will return true.

* *

At each incremental step of the scroll the caller should invoke * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} * once it has calculated the requested scrolling delta. If it returns true the nested scrolling * parent at least partially consumed the scroll and the caller should adjust the amount it * scrolls by.

* *

After applying the remainder of the scroll delta the caller should invoke * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat * these values differently. See * {@link NestedScrollingParent#onNestedScroll(View, int, int, int, int)}. *

* * @param axes Flags consisting of a combination of {@link ViewCompat#SCROLL_AXIS_HORIZONTAL} * and/or {@link ViewCompat#SCROLL_AXIS_VERTICAL}. * @return true if a cooperative parent was found and nested scrolling has been enabled for * the current gesture. * * @see #stopNestedScroll() * @see #dispatchNestedPreScroll(int, int, int[], int[]) * @see #dispatchNestedScroll(int, int, int, int, int[]) */ public boolean startNestedScroll(int axes); /** * Stop a nested scroll in progress. * *

Calling this method when a nested scroll is not currently in progress is harmless.

* * @see #startNestedScroll(int) */ public void stopNestedScroll(); /** * Returns true if this view has a nested scrolling parent. * *

The presence of a nested scrolling parent indicates that this view has initiated * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.

* * @return whether this view has a nested scrolling parent */ public boolean hasNestedScrollingParent(); /** * Dispatch one step of a nested scroll in progress. * *

Implementations of views that support nested scrolling should call this to report * info about a scroll in progress to the current nested scrolling parent. If a nested scroll * is not currently in progress or nested scrolling is not * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.

* *

Compatible View implementations should also call * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before * consuming a component of the scroll event themselves.

* * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view * @param offsetInWindow Optional. If not null, on return this will contain the offset * in local view coordinates of this view from before this operation * to after it completes. View implementations may use this to adjust * expected input coordinate tracking. * @return true if the event was dispatched, false if it could not be dispatched. * @see #dispatchNestedPreScroll(int, int, int[], int[]) */ public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow); /** * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. * *

Nested pre-scroll events are to nested scroll events what touch intercept is to touch. * dispatchNestedPreScroll offers an opportunity for the parent view in a nested * scrolling operation to consume some or all of the scroll operation before the child view * consumes it.

* * @param dx Horizontal scroll distance in pixels * @param dy Vertical scroll distance in pixels * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx * and consumed[1] the consumed dy. * @param offsetInWindow Optional. If not null, on return this will contain the offset * in local view coordinates of this view from before this operation * to after it completes. View implementations may use this to adjust * expected input coordinate tracking. * @return true if the parent consumed some or all of the scroll delta * @see #dispatchNestedScroll(int, int, int, int, int[]) */ public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow); /** * Dispatch a fling to a nested scrolling parent. * *

This method should be used to indicate that a nested scrolling child has detected * suitable conditions for a fling. Generally this means that a touch scroll has ended with a * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} * along a scrollable axis.

* *

If a nested scrolling child view would normally fling but it is at the edge of * its own content, it can use this method to delegate the fling to its nested scrolling * parent instead. The parent may optionally consume the fling or observe a child fling.

* * @param velocityX Horizontal fling velocity in pixels per second * @param velocityY Vertical fling velocity in pixels per second * @param consumed true if the child consumed the fling, false otherwise * @return true if the nested scrolling parent consumed or otherwise reacted to the fling */ public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed); /** * Dispatch a fling to a nested scrolling parent before it is processed by this view. * *

Nested pre-fling events are to nested fling events what touch intercept is to touch * and what nested pre-scroll is to nested scroll. dispatchNestedPreFling * offsets an opportunity for the parent view in a nested fling to fully consume the fling * before the child view consumes it. If this method returns true, a nested * parent view consumed the fling and this view should not scroll as a result.

* *

For a better user experience, only one view in a nested scrolling chain should consume * the fling at a time. If a parent view consumed the fling this method will return false. * Custom view implementations should account for this in two ways:

* *
    *
  • If a custom view is paged and needs to settle to a fixed page-point, do not * call dispatchNestedPreFling; consume the fling and settle to a valid * position regardless.
  • *
  • If a nested parent does consume the fling, this view should not scroll at all, * even to settle back to a valid idle position.
  • *
* *

Views should also not offer fling velocities to nested parent views along an axis * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} * should not offer a horizontal fling velocity to its parents since scrolling along that * axis is not permitted and carrying velocity along that motion does not make sense.

* * @param velocityX Horizontal fling velocity in pixels per second * @param velocityY Vertical fling velocity in pixels per second * @return true if a nested scrolling parent consumed the fling */ public boolean dispatchNestedPreFling(float velocityX, float velocityY);}
有9个函数,简单说明一下:

1,setNestedScrollingEnabled 实现该接口的View要调用setNestedScrollingEnabled(true)才可以使用嵌套滚动.

2,isNestedScrollingEnabled判断当前view能否使用嵌套滚动.

3,startNestedScroll和stopNestedScroll.是配对使用的.startNestedScroll表示view开始滚动了,一般是在ACTION_DOWN中调用,是来查找是否有嵌套处理的父View.在事件结束比如ACTION_UP或者ACTION_CANCLE中调用stopNestedScroll,告诉父布局滚动结束.

4dispatchNestedPreScroll,在该view消费滚动距离之前把总得滑动距离传给父布局.

5,dispatchNestedScroll,在该view消费滚动距离之后,把剩下的滑动距离再次传给父布局.

6,dispatchNestedFling和dispatchNestedPreFling就是把view传递滑动的信息给父布局的.比如滑动速度

NestedScrollingChildHelper这个类是一个辅助类就来把View的消息传递嵌套的父View。所以上面函数内部实现基本上都是调用NestedScrollingChildHelper这类的函数,咱看一个:

NestedScrollingChildHelper的startNestedScroll()函数,一般就是在NestedScrollingChild的startNestedScroll()函数里调用,参数表示方向,有两个值ViewCompat.SCROLL_AXIS_HORIZONTAL ,ViewCompat.SCROLL_AXIS_VERTICAL

public boolean startNestedScroll(int axes) {        if (hasNestedScrollingParent()) {            // Already in progress            return true;        }        if (isNestedScrollingEnabled()) {            ViewParent p = mView.getParent();            View child = mView;            while (p != null) {                if (ViewParentCompat.onStartNestedScroll(p, child, mView, axes)) {                    mNestedScrollingParent = p;                    ViewParentCompat.onNestedScrollAccepted(p, child, mView, axes);                    return true;                }                if (p instanceof View) {                    child = (View) p;                }                p = p.getParent();            }        }        return false;    }

上面就是寻找能够响应嵌套滑动的父View,也就是调用父类的onStartNestedScroll(),这个函数是NestedScrollingParent接口的函数,所以嵌套滑动的父View要实现这个接口,接着往下看,最后会有一个demo测试嵌套滑动

接着来看NestedScrollingParent这个接口:

/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package android.support.v4.view;import android.view.MotionEvent;import android.view.VelocityTracker;import android.view.View;import android.view.ViewConfiguration;/** * This interface should be implemented by {@link android.view.ViewGroup ViewGroup} subclasses * that wish to support scrolling operations delegated by a nested child view. * * 

Classes implementing this interface should create a final instance of a * {@link NestedScrollingParentHelper} as a field and delegate any View or ViewGroup methods * to the NestedScrollingParentHelper methods of the same signature.

* *

Views invoking nested scrolling functionality should always do so from the relevant * {@link ViewCompat}, {@link ViewGroupCompat} or {@link ViewParentCompat} compatibility * shim static methods. This ensures interoperability with nested scrolling views on Android * 5.0 Lollipop and newer.

*/public interface NestedScrollingParent { /** * React to a descendant view initiating a nestable scroll operation, claiming the * nested scroll operation if appropriate. * *

This method will be called in response to a descendant view invoking * {@link ViewCompat#startNestedScroll(View, int)}. Each parent up the view hierarchy will be * given an opportunity to respond and claim the nested scrolling operation by returning * true.

* *

This method may be overridden by ViewParent implementations to indicate when the view * is willing to support a nested scrolling operation that is about to begin. If it returns * true, this ViewParent will become the target view's nested scrolling parent for the duration * of the scroll operation in progress. When the nested scroll is finished this ViewParent * will receive a call to {@link #onStopNestedScroll(View)}. *

* * @param child Direct child of this ViewParent containing target * @param target View that initiated the nested scroll * @param nestedScrollAxes Flags consisting of {@link ViewCompat#SCROLL_AXIS_HORIZONTAL}, * {@link ViewCompat#SCROLL_AXIS_VERTICAL} or both * @return true if this ViewParent accepts the nested scroll operation */ public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes); /** * React to the successful claiming of a nested scroll operation. * *

This method will be called after * {@link #onStartNestedScroll(View, View, int) onStartNestedScroll} returns true. It offers * an opportunity for the view and its superclasses to perform initial configuration * for the nested scroll. Implementations of this method should always call their superclass's * implementation of this method if one is present.

* * @param child Direct child of this ViewParent containing target * @param target View that initiated the nested scroll * @param nestedScrollAxes Flags consisting of {@link ViewCompat#SCROLL_AXIS_HORIZONTAL}, * {@link ViewCompat#SCROLL_AXIS_VERTICAL} or both * @see #onStartNestedScroll(View, View, int) * @see #onStopNestedScroll(View) */ public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes); /** * React to a nested scroll operation ending. * *

Perform cleanup after a nested scrolling operation. * This method will be called when a nested scroll stops, for example when a nested touch * scroll ends with a {@link MotionEvent#ACTION_UP} or {@link MotionEvent#ACTION_CANCEL} event. * Implementations of this method should always call their superclass's implementation of this * method if one is present.

* * @param target View that initiated the nested scroll */ public void onStopNestedScroll(View target); /** * React to a nested scroll in progress. * *

This method will be called when the ViewParent's current nested scrolling child view * dispatches a nested scroll event. To receive calls to this method the ViewParent must have * previously returned true for a call to * {@link #onStartNestedScroll(View, View, int)}.

* *

Both the consumed and unconsumed portions of the scroll distance are reported to the * ViewParent. An implementation may choose to use the consumed portion to match or chase scroll * position of multiple child elements, for example. The unconsumed portion may be used to * allow continuous dragging of multiple scrolling or draggable elements, such as scrolling * a list within a vertical drawer where the drawer begins dragging once the edge of inner * scrolling content is reached.

* * @param target The descendent view controlling the nested scroll * @param dxConsumed Horizontal scroll distance in pixels already consumed by target * @param dyConsumed Vertical scroll distance in pixels already consumed by target * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by target * @param dyUnconsumed Vertical scroll distance in pixels not consumed by target */ public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed); /** * React to a nested scroll in progress before the target view consumes a portion of the scroll. * *

When working with nested scrolling often the parent view may want an opportunity * to consume the scroll before the nested scrolling child does. An example of this is a * drawer that contains a scrollable list. The user will want to be able to scroll the list * fully into view before the list itself begins scrolling.

* *

onNestedPreScroll is called when a nested scrolling child invokes * {@link View#dispatchNestedPreScroll(int, int, int[], int[])}. The implementation should * report how any pixels of the scroll reported by dx, dy were consumed in the * consumed array. Index 0 corresponds to dx and index 1 corresponds to dy. * This parameter will never be null. Initial values for consumed[0] and consumed[1] * will always be 0.

* * @param target View that initiated the nested scroll * @param dx Horizontal scroll distance in pixels * @param dy Vertical scroll distance in pixels * @param consumed Output. The horizontal and vertical scroll distance consumed by this parent */ public void onNestedPreScroll(View target, int dx, int dy, int[] consumed); /** * Request a fling from a nested scroll. * *

This method signifies that a nested scrolling child has detected suitable conditions * for a fling. Generally this means that a touch scroll has ended with a * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} * along a scrollable axis.

* *

If a nested scrolling child view would normally fling but it is at the edge of * its own content, it can use this method to delegate the fling to its nested scrolling * parent instead. The parent may optionally consume the fling or observe a child fling.

* * @param target View that initiated the nested scroll * @param velocityX Horizontal velocity in pixels per second * @param velocityY Vertical velocity in pixels per second * @param consumed true if the child consumed the fling, false otherwise * @return true if this parent consumed or otherwise reacted to the fling */ public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed); /** * React to a nested fling before the target view consumes it. * *

This method siginfies that a nested scrolling child has detected a fling with the given * velocity along each axis. Generally this means that a touch scroll has ended with a * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} * along a scrollable axis.

* *

If a nested scrolling parent is consuming motion as part of a * {@link #onNestedPreScroll(View, int, int, int[]) pre-scroll}, it may be appropriate for * it to also consume the pre-fling to complete that same motion. By returning * true from this method, the parent indicates that the child should not * fling its own internal content as well.

* * @param target View that initiated the nested scroll * @param velocityX Horizontal velocity in pixels per second * @param velocityY Vertical velocity in pixels per second * @return true if this parent consumed the fling ahead of the target view */ public boolean onNestedPreFling(View target, float velocityX, float velocityY); /** * Return the current axes of nested scrolling for this NestedScrollingParent. * *

A NestedScrollingParent returning something other than {@link ViewCompat#SCROLL_AXIS_NONE} * is currently acting as a nested scrolling parent for one or more descendant views in * the hierarchy.

* * @return Flags indicating the current axes of nested scrolling * @see ViewCompat#SCROLL_AXIS_HORIZONTAL * @see ViewCompat#SCROLL_AXIS_VERTICAL * @see ViewCompat#SCROLL_AXIS_NONE */ public int getNestedScrollAxes();}

8个函数,简单介绍一下:

1,onStartNestedScroll.当子view的调用NestedScrollingChild的方法startNestedScroll时,会调用该方法.前面分析到了

2,onNestedScrollAccepted.如果onStartNestedScroll方法返回的是true的话,那么紧接着就会调用该方法.它是让嵌套滚动在开始滚动之前,让布局容器(viewGroup)或者它的父类执行一些配置的初始化的.

3,onStopNestedScroll停止滚动了,当子view调用stopNestedScroll时会调用该方法.

4,onNestedScroll,当子view调用dispatchNestedScroll方法时,会调用该方法.

5,onNestedPreScroll,当子view调用dispatchNestedPreScroll方法是,会调用该方法.

6,dispatchNestedFling和dispatchNestedPreFling对应的就是滑动了.

同样NestedScrollingParent也有一个帮助类NestedScrollingParentHelper来实现嵌套滑动

由上可以知道这四个类(接口)两两对应,下面一个表格表示对应方法调用顺序,借了一张图过来


还有另外两个对应函数没贴上。

下面通过一个demo来测试一下,毕竟讲的再多不如实践一次

来张效果图:


demo实现就是滑动子View的时候如果滑动距离小于某个值,就只平移父View(滑动距离全部给父View消耗),当大于这个值时,两者之差的值就让子View平移,这里只是测试函数调用顺序,一些数据处理大家不要在意哈。 看代码: 子View:
package cj.com.nestedscrollingdemo;import android.content.Context;import android.support.v4.view.NestedScrollingChildHelper;import android.support.v4.view.ViewCompat;import android.util.AttributeSet;import android.util.Log;import android.view.MotionEvent;import android.view.View;public class NestScrollingView extends View {    private static final String TAG = "Test";    private NestedScrollingChildHelper mChildHelper;    private int[] mConsumed = new int[2];    private int[] mOffset = new int[2];    public NestScrollingView(Context context) {        super(context);        init();    }    public NestScrollingView(Context context, AttributeSet attrs) {        super(context, attrs);        init();    }    public NestScrollingView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init();    }    private void init() {        mChildHelper = new NestedScrollingChildHelper(this);        setNestedScrollingEnabled(true);    }    @Override    public void setNestedScrollingEnabled(boolean enabled) {        mChildHelper.setNestedScrollingEnabled(enabled);    }    @Override    public boolean isNestedScrollingEnabled() {        return mChildHelper.isNestedScrollingEnabled();        //return super.isNestedScrollingEnabled();    }    @Override    public boolean startNestedScroll(int axes) {//        Log.d(TAG, "NestScrollingView  startNestedScroll");        return mChildHelper.startNestedScroll(axes);        //return super.startNestedScroll(axes);    }    @Override    public void stopNestedScroll() {        Log.d(TAG, "NestScrollingView  stopNestedScroll");        mChildHelper.stopNestedScroll();       // super.stopNestedScroll();    }    @Override    public boolean hasNestedScrollingParent() {        Log.d(TAG, "NestScrollingView  hasNestedScrollingParent");        return mChildHelper.hasNestedScrollingParent();        //return super.hasNestedScrollingParent();    }    @Override    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {        Log.d(TAG, "NestScrollingView  dispatchNestedScroll");        return mChildHelper.dispatchNestedScroll(dxConsumed,dyConsumed,                dxUnconsumed,dyUnconsumed,offsetInWindow);        //return super.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow);    }    /**     *     * @param dx X方向的偏移量 传给父View 先让父View处理     * @param dy y方向的偏移量     * @param consumed  一个数组,   表示 x 方向 或 y 方向的偏移量 是否有被父View消费 返回的数据是父View消耗了多少     * @param offsetInWindow  父View消费滑动事件后 导致该View的偏移量  这个由NestedScrollingChildHelper内部处理     * @return  父View 是否消耗了传入的偏移     */    @Override    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {        Log.d(TAG, "NestScrollingView  dispatchNestedPreScroll");        return mChildHelper.dispatchNestedPreScroll(dx,dy,                consumed,offsetInWindow);       // return super.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);    }    @Override    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {        Log.d(TAG, "NestScrollingView  dispatchNestedFling");        return mChildHelper.dispatchNestedFling(velocityX,velocityY,                consumed);    }    @Override    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {        Log.d(TAG, "NestScrollingView  dispatchNestedPreFling");        return mChildHelper.dispatchNestedPreFling(velocityX,velocityY);    }    private int lastX;    private int lastY;    @Override    public boolean onTouchEvent(MotionEvent event) {        switch (event.getAction()) {            case MotionEvent.ACTION_DOWN:                Log.d(TAG, "onTouchEvent  ACTION_DOWN ");                // 按下事件调用startNestedScroll                lastX = (int) event.getX();                lastY = (int) event.getY();                Log.d(TAG, "onTouchEvent  lastX = "+lastX+"  lasty="+lastY);                startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);                break;            case MotionEvent.ACTION_MOVE:                Log.d(TAG, "onTouchEvent  ACTION_MOVE ");                int x = (int) event.getX();                int y = (int) event.getY();                int deltaX = x - lastX;                int deltaY = y - lastY;                Log.d(TAG, "onTouchEvent  x = "+x+"  y="+y);                Log.d(TAG, "onTouchEvent  deltaX = "+deltaX+"  deltaY="+deltaY);                dispatchNestedPreScroll(deltaX,deltaY,mConsumed,mOffset);                Log.d(TAG, "onTouchEvent  mConsumed[0] = "+mConsumed[0]+"  mConsumed[1] = "+mConsumed[1]);                Log.d(TAG, "onTouchEvent  offsetX = " + mOffset[0] + ",offsetY = " + mOffset[1]);                if(deltaY>mConsumed[1]){                    setTranslationY(deltaY-mConsumed[1]);                }                dispatchNestedScroll(0,deltaY,deltaX,0,mOffset);                break;            case MotionEvent.ACTION_UP:                Log.d(TAG, "onTouchEvent  ACTION_UP ");                stopNestedScroll();                break;            default:                break;        }        return true;    }}

因为我是在API 24上开发的,所以只要继承View可以,因为View已经实现NestedScrollingChild接口的所有函数,为了安全起见,最好还是实现这个接口,事件的开始由子View开始,所以在onTouchEvent()函数里开始和父View一起处理事件。 父View:同样父View最好也实现NestedScrollingParent接口
package cj.com.nestedscrollingdemo;import android.content.Context;import android.support.v4.view.NestedScrollingChild;import android.support.v4.view.NestedScrollingParent;import android.support.v4.view.NestedScrollingParentHelper;import android.support.v4.view.ViewCompat;import android.util.AttributeSet;import android.util.Log;import android.view.View;import android.widget.FrameLayout;/** * */public class NestScrollingViewGroup extends FrameLayout {    private NestedScrollingParentHelper mParentHelper;    private static final String TAG = "Test";    public NestScrollingViewGroup(Context context, AttributeSet attrs) {        super(context, attrs);        init();    }    public NestScrollingViewGroup(Context context) {        super(context);        init();    }    public NestScrollingViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init();    }    private void init() {        mParentHelper = new NestedScrollingParentHelper(this);    }    @Override    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {        Log.d(TAG, "NestScrollingViewGroup  onStartNestedScroll  nestedScrollAxes ="+nestedScrollAxes);        return (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;    }    @Override    public void onNestedScrollAccepted(View child, View target, int axes) {        Log.d(TAG, "NestScrollingViewGroup  onNestedScrollAccepted axes="+axes);        mParentHelper.onNestedScrollAccepted(child, target, axes);    }    @Override    public void onStopNestedScroll(View child) {        Log.d(TAG, "NestScrollingViewGroup  onStopNestedScroll");        mParentHelper.onStopNestedScroll(child);    }    @Override    public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {        Log.d(TAG, "NestScrollingViewGroup  onNestedScroll");        Log.d(TAG, "    dxConsumed="+dxConsumed+"   dyConsumed="+dyConsumed+"   dxUnconsumed="+dxUnconsumed+"   dyUnconsumed="+dyUnconsumed);    }    @Override    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {        Log.d(TAG, "NestScrollingViewGroup  onNestedPreScroll");        Log.d(TAG, "    dx="+dx+"   dy="+dy+"   consumed[0]="+consumed[0]+"   consumed[1]="+consumed[1]);        if(dy<=80){            setTranslationY(dy);            consumed[0] = 0;            consumed[1] = dy;        }else{          //...            setTranslationY(80);            consumed[0] = 0;            consumed[1] = 80;        }    }    @Override    public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {        Log.d(TAG, "NestScrollingViewGroup  onNestedFling");        return super.onNestedFling(target, velocityX, velocityY, consumed);    }    @Override    public boolean onNestedPreFling(View target, float velocityX, float velocityY) {        Log.d(TAG, "NestScrollingViewGroup  onNestedPreFling");        return super.onNestedPreFling(target, velocityX, velocityY);    }    @Override    public int getNestedScrollAxes() {        Log.d(TAG, "NestScrollingViewGroup  getNestedScrollAxes");        return mParentHelper.getNestedScrollAxes();    }}

布局文件:
<?xml version="1.0" encoding="utf-8"?>    
看一下log:
D/Test: NestScrollingView  stopNestedScrollD/Test: onTouchEvent  ACTION_DOWN D/Test: onTouchEvent  lastX = 261  lasty=269D/Test: NestScrollingView  startNestedScrollD/Test: NestScrollingViewGroup  onStartNestedScroll  nestedScrollAxes =2D/Test: NestScrollingViewGroup  onNestedScrollAccepted axes=2D/Test: onTouchEvent  ACTION_MOVE D/Test: onTouchEvent  x = 264  y=276D/Test: onTouchEvent  deltaX = 3  deltaY=7D/Test: NestScrollingView  dispatchNestedPreScrollD/Test: NestScrollingViewGroup  onNestedPreScrollD/Test:     dx=3   dy=7   consumed[0]=0   consumed[1]=0D/Test: onTouchEvent  mConsumed[0] = 0  mConsumed[1] = 7D/Test: onTouchEvent  offsetX = 0,offsetY = 7D/Test: NestScrollingView  dispatchNestedScrollD/Test: NestScrollingViewGroup  onNestedScrollD/Test:     dxConsumed=0   dyConsumed=7   dxUnconsumed=3   dyUnconsumed=0D/Test: onTouchEvent  ACTION_MOVE D/Test: onTouchEvent  x = 261  y=282D/Test: onTouchEvent  deltaX = 0  deltaY=13D/Test: NestScrollingView  dispatchNestedPreScrollD/Test: NestScrollingViewGroup  onNestedPreScrollD/Test:     dx=0   dy=13   consumed[0]=0   consumed[1]=0D/Test: onTouchEvent  mConsumed[0] = 0  mConsumed[1] = 13D/Test: onTouchEvent  offsetX = 0,offsetY = 6D/Test: NestScrollingView  dispatchNestedScrollD/Test: NestScrollingViewGroup  onNestedScrollD/Test:     dxConsumed=0   dyConsumed=13   dxUnconsumed=0   dyUnconsumed=0D/Test: onTouchEvent  ACTION_MOVE D/Test: onTouchEvent  x = 258  y=283D/Test: onTouchEvent  deltaX = -3  deltaY=14D/Test: NestScrollingView  dispatchNestedPreScrollD/Test: NestScrollingViewGroup  onNe
log没贴完全,有点多,通过这一部分就可以知道流程了

通过一个小demo,可以加深我们对嵌套滑动机制的理解。 android滑动嵌套应用还是蛮多的。比如CoordinatorLayout及子view使用Behavior来实现嵌套滑动,Behavior内部都有NestedScrollingChild,NestedScrollingParent的相似的函数。




更多相关文章

  1. 【Android经典入门教程-下(bill译)】
  2. android 五大布局经典演绎
  3. Android字体加粗
  4. Android高性能编程(1)--基础篇
  5. Android(安卓)滑动效果高级篇(七)—— 华丽翻页效果
  6. 一个使用FFmpeg库读取3gp视频的例子-Android中使用FFmpeg媒体库(
  7. android shape ring 画一个多层嵌套的圆环和圆角图片
  8. 五成Android设备要向微软支付专利费
  9. Android(安卓)studio安装配置常见问题及其解决方案

随机推荐

  1. 关于Android的HAL的一些理解
  2. Android消息传递之EventBus 3.0使用详解
  3. Android攻城略地,Nokia何去何从?
  4. Cordova下android与javascript的交互
  5. 位Android开发人员的收入报告
  6. Study on Android【一】--概述
  7. nexus 7 诡异的分辨率问题
  8. HttpClient android
  9. Android 桌面组件【app widget】 进阶项
  10. 45套精美的 ( Android, iPhone, iPad )