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表示不能往下滑動,即代表到頂部了;

     

 

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