如何知道 RecyclerView/LinearLayoutManager 是滚动到顶部还是底部? [英] How to know whether a RecyclerView / LinearLayoutManager is scrolled to top or bottom?
问题描述
目前我正在使用以下代码来检查是否应启用 SwipeRefreshLayout.
Currently I am using the follow code to check whether SwipeRefreshLayout should be enabled.
private void laySwipeToggle() {
if (mRecyclerView.getChildCount() == 0 || mRecyclerView.getChildAt(0).getTop() == 0) {
mLaySwipe.setEnabled(true);
} else {
mLaySwipe.setEnabled(false);
}
}
但这就是问题所在.当它滚动到另一个项目的视图边界时 mRecyclerView.getChildAt(0).getTop()
也返回 0.
But here is the problem. When it's scrolled to another item's view's boundary mRecyclerView.getChildAt(0).getTop()
also returns 0.
是否有类似 RecyclerView.isScrolledToBottom()
或 RecyclerView.isScrolledToTop()
之类的东西?
Is there something like RecyclerView.isScrolledToBottom()
or RecyclerView.isScrolledToTop()
?
(mRecyclerView.getChildAt(0).getTop() == 0 && linearLayoutManager.findFirstVisibleItemPosition() == 0)
类型的 RecyclerView.isScrolledToTop()
,但是 RecyclerView.isScrolledToBottom()
呢?
(mRecyclerView.getChildAt(0).getTop() == 0 && linearLayoutManager.findFirstVisibleItemPosition() == 0)
kind of does the RecyclerView.isScrolledToTop()
, but what about RecyclerView.isScrolledToBottom()
?
推荐答案
解决方案在布局管理器中.
The solution is in the layout manager.
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// Add this to your Recycler view
recyclerView.setLayoutManager(layoutManager);
// To check if at the top of recycler view
if(layoutManager.firstCompletelyVisibleItemPosition()==0){
// Its at top
}
// To check if at the bottom of recycler view
if(layoutManager.lastCompletelyVisibleItemPosition()==data.size()-1){
// Its at bottom
}
编辑
如果您的项目尺寸大于屏幕,请使用以下方法检测顶部事件.
In case your item size is larger than the screen use the following to detect the top event.
RecyclerView recyclerView = (RecyclerView) view;
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
int pos = linearLayoutManager.findFirstVisibleItemPosition();
if(linearLayoutManager.findViewByPosition(pos).getTop()==0 && pos==0){
return true;
}
PS:实际上,如果您将 RecyclerView
直接放在 SwipeRefreshview
中,您就不需要这样做
PS: Actually, if you place the RecyclerView
directly inside the SwipeRefreshview
you wouldn't need to do this
这篇关于如何知道 RecyclerView/LinearLayoutManager 是滚动到顶部还是底部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!