Android Recyclerview判斷是否已經到底部或者頂部
在實際處理業務的時候經常會需要判斷列表是否到底部或者頂部,現在基本都是用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表示不能往下滑動,即代表到頂部了;