Android Recyclerview判断是否已经到底部或者顶部

在实际处理业务的时候经常会需要判断列表是否到底部或者顶部,现在基本都是用RecyclerView来做列表,这里SDK提供了一个方法非常简单就可以解决,

// 垂直方向的判断
 


 
  1. /**

  2. * Check if this view can be scrolled vertically in a certain direction.

  3. *

  4. * @param direction Negative to check scrolling up, positive to check scrolling down.

  5. * @return true if this view can be scrolled in the specified direction, false otherwise.

  6. */

  7. public boolean canScrollVertically(int direction) {

  8. final int offset = computeVerticalScrollOffset();

  9. final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();

  10. if (range == 0) return false;

  11. if (direction < 0) {

  12. return offset > 0;

  13. } else {

  14. return offset < range - 1;

  15. }

  16. }
     

    computeVerticalScrollOffset:计算控件垂直方向的偏移值,

    computeVerticalScrollExtent:计算控件可视的区域,

    computeVerticalScrollRange:计算控件垂直方向的滚动范围

    // 水平方向的判断
     

    
     
  17. /**

  18. * Check if this view can be scrolled horizontally in a certain direction.

  19. *

  20. * @param direction Negative to check scrolling left, positive to check scrolling right.

  21. * @return true if this view can be scrolled in the specified direction, false otherwise.

  22. */

  23. public boolean canScrollHorizontally(int direction) {

  24. final int offset = computeHorizontalScrollOffset();

  25. final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();

  26. if (range == 0) return false;

  27. if (direction < 0) {

  28. return offset > 0;

  29. } else {

  30. return offset < range - 1;

  31. }

  32. }


  33. 这个是View里面的方法,经过使用未发现BUG,使用的时候直接调用这个方法就好了,

     

    比如:判断是否滑动到底部, recyclerView.canScrollVertically(1);返回false表示不能往上滑动,即代表到底部了;

                判断是否滑动到顶部, recyclerView.canScrollVertically(-1);返回false表示不能往下滑动,即代表到顶部了;

     

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章