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
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();
}
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;
}
In Kotlin you can do :
fun isRecyclerScrollable(): Boolean {
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val adapter = recyclerView.adapter
return if (adapter == null) false else layoutManager.findLastCompletelyVisibleItemPosition() < adapter.itemCount - 1
}
Use this approach:
recyclerView.viewTreeObserver.addOnScrollChangedListener {
val canScrollUp = recyclerView.canScrollVertically(-1)
val canScrollDown = recyclerView.canScrollVertically(1)
}
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
}
});
}
I had the same problem and the answers already posted, especially Fabios, brought me on the right track. The scrollRange does not support paddings though, so they need to taken into account as well if your Recyclerview has a padding.
I'm using the following extension property in Kotlin now to determine whether or not the view is scrolling.
/**
* computes whether the RecyclerView's content is larger than the view container, i.e. whether or not the user can scroll
* returns null if either layout manager or adapter is not yet set or an incompatible layout manager is used (Linear- & GridLayoutManager work)
*/
val RecyclerView.canScroll: Boolean?
get() {
// if there's no adapter set, we don't know yet whether or not the view is scrollable
if (adapter == null) return null
val manager = layoutManager as? LinearLayoutManager ?: return null
if (manager.orientation == RecyclerView.HORIZONTAL) {
return computeHorizontalScrollRange() + paddingLeft + paddingRight > width
}
return computeVerticalScrollRange() + paddingTop + paddingBottom > height
}