在实际处理业务的时候经常会需要判断列表是否到底部或者顶部,现在基本都是用RecyclerView来做列表,这里SDK提供了一个方法非常简单就可以解决,
// 垂直方向的判断
/**
* Check if this view can be scrolled vertically in a certain direction.
*
* @param direction Negative to check scrolling up, positive to check scrolling down.
* @return true if this view can be scrolled in the specified direction, false otherwise.
*/
public boolean canScrollVertically(int direction) {
final int offset = computeVerticalScrollOffset();
final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
if (range == 0) return false;
if (direction < 0) {
return offset > 0;
} else {
return offset < range - 1;
}
}
computeVerticalScrollOffset:计算控件垂直方向的偏移值,
computeVerticalScrollExtent:计算控件可视的区域,
computeVerticalScrollRange:计算控件垂直方向的滚动范围
// 水平方向的判断
/**
* Check if this view can be scrolled horizontally in a certain direction.
*
* @param direction Negative to check scrolling left, positive to check scrolling right.
* @return true if this view can be scrolled in the specified direction, false otherwise.
*/
public boolean canScrollHorizontally(int direction) {
final int offset = computeHorizontalScrollOffset();
final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
if (range == 0) return false;
if (direction < 0) {
return offset > 0;
} else {
return offset < range - 1;
}
}
这个是View里面的方法,经过使用未发现BUG,使用的时候直接调用这个方法就好了,
比如:判断是否滑动到底部, recyclerView.canScrollVertically(1);返回false表示不能往上滑动,即代表到底部了;
判断是否滑动到顶部, recyclerView.canScrollVertically(-1);返回false表示不能往下滑动,即代表到顶部了;
其他的方向的判断同理,在这里做个记录