您的位置:首页 > 其它

安卓RecyclerView视图滑动对齐不到顶部(底部)的校准

2016-05-18 12:26 543 查看
RecyclerView在滑动到顶部的时候,继续向下拖拽,再放开,会有一个类似弹性的效果,整体上会向上稍微移动一点。这种效果在目前很多主流的App类list视图界面上都存在,譬如微信首页。那么自然会有一个问题:如果需要保证RecyclerView下拉到顶部的时候,稳定在顶部,不能有上述的弹性效果,怎么实现呢?看了一下目前的RecyclerView相关api,没有找到官方配置的方法。最后采用下述方法进行校准:
在RecyclerView.OnScrollListener.onScrolled() 中,增加校准逻辑:
设置校准阈值private final int MAX_TOP_GAP = 20;

if (getChildCount() > 0 && 0 == getChildViewHolder(getChildAt(0)).getAdapterPosition()
&& SCROLL_STATE_SETTLING == getScrollState()) {
final int top = getChildAt(0).getTop();
if (-1 * MAX_TOP_GAP <= top && MAX_TOP_GAP >= top) {
scrollToPosition(0);
}
}

当最后一次的滑动后最顶部的字View的Top值小于阈值,强制滑回positon 0.
说明:
(1)SCROLL_STATE_SETTLING== getScrollState()的意义?
RecyclerView官方Api给出了scroll state的概念,可以用getScrollState()获取。下面是官方文档的状态值介绍:
SCROLL_STATE_DRAGGING
int SCROLL_STATE_DRAGGING
The RecyclerView is currently being dragged by outside input such as user touch input.
See also:
getScrollState()
Constant Value: 1 (0x00000001)
SCROLL_STATE_IDLE
int SCROLL_STATE_IDLE
The RecyclerView is not currently scrolling.
See also:
getScrollState()
Constant Value: 0 (0x00000000)
SCROLL_STATE_SETTLING
int SCROLL_STATE_SETTLING
The RecyclerView is currently animating to a final position while not under outside control.
See also:
getScrollState()
Constant Value: 2 (0x00000002)
SCROLL_STATE_SETTLING即滑动手势结束后(松开手指后),到停止在最终位置之前,自动滑动的状态。从实际测试来看,回弹的过程是处于此状态。所以将此状态作为是否强制校准的判断条件之一。
(2)0== getChildViewHolder(getChildAt(0)).getAdapterPosition()
的目的?
这个条件判断当前可见的第一个child是否是Adapter中的第一个,即判断是否已经上滑到顶。RecyclerView会将不可见的child view回收,所以getChildAt(0)得到的view不能保证是Adapter中的第一个。
以上为校准顶部位置的方法。底部同理,不详述。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: