转载请标明出处: 【明明爱的博客】
概述
目前recycleview很火热,基本可以代替ListView、GridView。横向listView更是在目前很多app中有在运用,但横向recycleview模式一直往左拉数据太多交互就不舒服了,其实更好的是有个向以前下拉更新似的功能,这里就是:左拉更新,上图。
分析
其实这里要做的就是怎样滑动的时候出现左拉更新,像以前我们都是加个footView,其实可以用ScrollView做,但这里我是用RecycleView来做。
- recycleView怎样加上footView(默认是没有addFootView方法的)
- 怎样监测已经滑到最后一个
- 滑动的距离怎么算
- 滑动到最后一个时,如果我往回滑,或者手放开怎样监测
- 滑动时怎样做出像ios的弹簧效果
好了,带着这些疑问我们来一步步解开。
良好的编程习惯,当你对某些控件不熟悉的时候,除了百度、google之外,最好的就是去看源码。
public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild {
}
其实RecyclerView 也是继承ViewGroup而已,说明流程还是像我们写自定义view一样的,为什么它那么强大,所以更要好好看看究竟是怎么写的,从中学习,因为我们不是为了学习RecycleView,所以我就直接说了。
/**
* An OnScrollListener can be added to a RecyclerView to receive messages when a scrolling event
* has occurred on that RecyclerView.
* <p>
* @see RecyclerView#addOnScrollListener(OnScrollListener)
* @see RecyclerView#clearOnChildAttachStateChangeListeners()
*
*/
public abstract static class OnScrollListener {
/**
* Callback method to be invoked when RecyclerView's scroll state changes.
*
* @param recyclerView The RecyclerView whose scroll state has changed.
* @param newState The updated scroll state. One of {@link #SCROLL_STATE_IDLE},
* {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}.
*/
public void onScrollStateChanged(RecyclerView recyclerView, int newState){}
/**
* Callback method to be invoked when the RecyclerView has been scrolled. This will be
* called after the scroll has completed.
* <p>
* This callback will also be called if visible item range changes after a layout
* calculation. In that case, dx and dy will be 0.
*
* @param recyclerView The RecyclerView which scrolled.
* @param dx The amount of horizontal scroll.
* @param dy The amount of vertical scroll.
*/
public void onScrolled(RecyclerView recyclerView, int dx, int dy){}
}
这里的接口很像我们以前用ListView的方法,没错,滑动的距离怎么算、目前RecycleView有没有在滑动都能得出来(根据newState字段)。但这里并不能知道当滑动时MotionEvent_UP、MotionEvent_MOVE状态,这时我们很容易想到继承RecycleView来写OnTouchEvent()事件,强大的RecycleView当然会想到用户会用到滑动事件,根据主体不变扩展的设计模式,一定会有接口的。果然:
public static interface OnItemTouchListener {
/**
* Silently observe and/or take over touch events sent to the RecyclerView
* before they are handled by either the RecyclerView itself or its child views.
*
* <p>The onInterceptTouchEvent methods of each attached OnItemTouchListener will be run
* in the order in which each listener was added, before any other touch processing
* by the RecyclerView itself or child views occurs.</p>
*
* @param e MotionEvent describing the touch event. All coordinates are in
* the RecyclerView's coordinate system.
* @return true if this OnItemTouchListener wishes to begin intercepting touch events, false
* to