最近在写关于RecyclerView滑动到最底部时,给出一个判断,是否到达最底部。但不知道为什么,总是得不到ScrollY,一直为0。没办法,只能去网上找一些相关资料。
非常感谢知乎用户-张宇 给的想法。原理很简单,主要就是获取item的高度,和item的总数,然后去计算总的长度。
废话不多说,代码贴上:
/**
* 还能向下滑动多少
*/
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;
}
计算RecyclerView已经滑动的距离。
/**
* 获取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;
}