Misha Bulasov
Misha Bulasov

Reputation: 1

RecyclerView.addOnScrollListener in NestedScrollView

NestedScrollView is within RecyclerView. When this RecyclerView instantiates an addOnScrollListener, the listener works correctly, but I cannot do pagination, nor can I properly track RecyclerView items on the screen. When RecyclerView is not a NestedScrollView, everything works well

 <android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="100dp" />
        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>           
    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

Upvotes: 0

Views: 356

Answers (1)

Matias Irland Tomas
Matias Irland Tomas

Reputation: 53

I think this is related to this post.

You should try adding a OnScrollChangeListener to your NestedScrollView.

public abstract class OnDemandRecyclerViewScrollListener implements NestedScrollView.OnScrollChangeListener {
  private final RecyclerView recyclerView;

  private int previousRecyclerViewHeight;
  private boolean loading = true;
  private int page = 1;

  private boolean enabled = true;
  @Dimension(unit = Dimension.PX)
  private int visibleThreshold = 0;

  public OnDemandRecyclerViewScrollListener(RecyclerView recyclerView) {
    this.recyclerView = recyclerView;
    loadNextPage(page);
  }


  @Override
  public void onScrollChange(NestedScrollView nestedScrollView, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    if (previousRecyclerViewHeight < recyclerView.getMeasuredHeight()) {
      loading = false;
      page++;
      previousRecyclerViewHeight = recyclerView.getMeasuredHeight();
    }

    if ((scrollY + visibleThreshold >= (recyclerView.getMeasuredHeight() - nestedScrollView.getMeasuredHeight())) &&
        scrollY > oldScrollY && !loading && enabled) {
      loading = true;
      loadNextPage(page);
    }
  }

  protected abstract void loadNextPage(int page);
}

Upvotes: 2

Related Questions