最近在写关于RecyclerView滑动到最底部时,给出一个判断,是否到达最底部。但不知道为什么,总是得不到ScrollY,一直为0。没办法,只能去网上找一些相关资料。但因为是实习生,自定义RecycleView这些很多都看不懂,只能去找最简单的办法。下面就是我找到的办法,在这里记录一下。非常感谢知乎用户-张宇 给的解法。
废话不多说,代码贴上:
/**
* 还能向下滑动多少
*/
private int getDistance(){
LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
View firstVisibItem = mRecyclerView.getChildAt(0);
int firstItemPosition = layoutManager.findFirstVisibleItemPosition();
int itemCount = layoutManager.getItemCount();
int recycleViewHeight = mRecyclerView.getHeight();
int itemHeight = firstVisibItem.getHeight();
int firstItemBottom = layoutManager.getDecoratedBottom(firstVisibItem);
return (itemCount - firstItemPosition - 1)* itemHeight - recycleViewHeight+firstItemBottom;
}
当前的getDistance()就是剩余的距离。
/**
* 已滑动的距离
*/
private int getDistance(){
LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
View firstVisibItem = mRecyclerView.getChildAt(0);
int firstItemPosition = layoutManager.findFirstVisibleItemPosition();
int itemCount = layoutManager.getItemCount();
int recycleViewHeight = mRecyclerView.getHeight();
int itemHeight = firstVisibItem.getHeight();
int firstItemBottom = layoutManager.getDecoratedBottom(firstVisibItem);
return (firstItemPosition + 1)*itemHeight - firstItemBottom;
}
当前的getDistance()就是已经滑动的距离了。然后我根据这个人的算法,判断自己有没有滑倒最底部了。
/**
* 获取RecyclerView滚动位置
*/
private int getDistance(){
LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
View firstVisibItem = mRecyclerView.getChildAt(0);
int firstItemPosition = layoutManager.findFirstVisibleItemPosition();
int itemCount = layoutManager.getItemCount();
int recycleViewHeight = mRecyclerView.getHeight();
int itemHeight = firstVisibItem.getHeight();
int firstItemBottom = layoutManager.getDecoratedBottom(firstVisibItem);
return (itemCount - firstItemPosition - 1)* itemHeight - recycleViewHeight;
}
这样当getDistance()等于0时,我就知道已经滑动到最底部了。如果你们RecyclerView上面有间距,自己看一下getDistance()等于多少。