How to check if a RecyclerView
is scrollable, ie, there are items below/above the visible area
I have a dropdown in my recycler view which works by using notifyItemRangeInserted()
and notifyItemRangeRemoved()
. Whenever any of this happens, I want to check if the RecyclerView
is scrollable or not, as I have to adjust another view, a banner like in newsstand, accordingly
You can use Scroll listener to detect scroll up or down changes in RecyclerView . RecycleView invokes the onScrollStateChanged() method before onScrolled() method. The onScrollStateChanged() method provides you the RecycleView's status: SCROLL_STATE_IDLE : No scrolling.
canScrollVertically(1) && dy > 0) { //scrolled to BOTTOM }else if (! recyclerView. canScrollVertically(-1) && dy < 0) { //scrolled to TOP } } }); This is simple and will hit exactly one time under all conditions when you have scrolled to the top or bottom.
There you go:
public boolean isRecyclerScrollable() {
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (layoutManager == null || adapter == null) return false;
return layoutManager.findLastCompletelyVisibleItemPosition() < adapter.getItemCount() - 1;
}
I found an easy solution that works regardless of the position you are in the list:
public boolean isRecyclerScrollable(RecyclerView recyclerView) {
return recyclerView.computeHorizontalScrollRange() > recyclerView.getWidth() || recyclerView.computeVerticalScrollRange() > recyclerView.getHeight();
}
The idea is to check if the last completely visible element is the last element in the list.
private boolean isScrollable()
{
return mLinearLayoutManager.findLastCompletelyVisibleItemPosition() + 1 ==
mRecyclerViewAdapter.getItemCount();
}
This one works for me.
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
boolean isRecylerScrollable = recyclerView.computeHorizontalScrollRange() > recyclerView.getWidth();
if(isRecylerScrollable){
//do something
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With