Reputation: 168
I'm using swiperefreshlayout and recyclerview in my project. i want swiperefreshlayout disable when recyclerview not on the first item. how can i do it? I have some code but it didn't work:
int topRowVerticalPosition = (myRecyclerView == null || myRecyclerView.getChildCount() == 0) ? 0 : myRecyclerView.getChildAt(0).getTop();
swipeRefreshLayout.setEnabled(layoutManager.findFirstCompletelyVisibleItemPosition() == 0 && topRowVerticalPosition >= 0);
Upvotes: 1
Views: 994
Reputation: 1658
Basically checking if the first visible item index == 0
is not correct, because you can hide it, My solution to this problem is to check the index if the first visible child is completely visible inside the recycler.
val isScrolledToTop = layout.findFirstCompletelyVisibleItemPosition() == indexOfChild(children.firstOrNull { it.isVisible }))
so you can combine it with a listener to enable Swipe to refresh.
binding.recyclerView.addOnScrollListener(object : OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
val isScrolledToTop = layout.findFirstCompletelyVisibleItemPosition() == indexOfChild(children.firstOrNull { it.isVisible }))
binding.swipeToRefresh.isEnabled = isScrolledToTop
}
}
Upvotes: 1
Reputation: 13932
You need to add an OnScrollListener to the RecyclerView
like so, and you can enable/disable the swipeRefreshLayout using the RecyclerView
s first child's visibility:
myRecyclerView.addOnScrollListener(new OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
View firstChild = recyclerView.getChildAt(0);
swipeRefreshLayout.setEnabled(firstChild.getVisibility() == View.VISIBLE);
}
});
Upvotes: 1