Farid
Farid

Reputation: 168

How can i disable swipe refresh layout when RecyclerView is not on the first item?

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

Answers (2)

abd3lraouf
abd3lraouf

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

kandroidj
kandroidj

Reputation: 13932

You need to add an OnScrollListener to the RecyclerView like so, and you can enable/disable the swipeRefreshLayout using the RecyclerViews 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

Related Questions