Reputation: 3245
I have a recyclerView
inside nestedScrollView
. I know it's a bad practice, but there are some cases, that I can handle only in this way.
<androidx.core.widget.NestedScrollView
android:id="@+id/nestedScroll"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:itemCount="1"
tools:listitem="@layout/item_favorite_tournament"
tools:visibility="visible" />
</androidx.core.widget.NestedScrollView>
And here's my code. I'll show you the scroll part, where I need to get the firstVisibleItemPosition
. But it returns 0.
private void initList(RecyclerView recycler, View labelNoResults) {
recycler.setAdapter(mAdapter);
recycler.setHasFixedSize(true);
mListLayoutManager = Objects.requireNonNull((LinearLayoutManager) recycler.getLayoutManager());
recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
final int p = mListLayoutManager.findFirstVisibleItemPosition();
Log.d("Tag_1", "Position: " + p);
}
});
}
I think the problem is because of nestedScrollView
. So how can I get the visibleItemPosition form recyclerView
? Thank you.
Upvotes: 4
Views: 2082
Reputation: 140
The easiest way to fix this would be to replace NestedScrollView
by simply ScrollView
. This of course will change the behavior of your layout, but it will show you the right position.
In case of NestedScrollView
, findFirstVisibleItemPosition()
always returns 0
and findLastVisibleItemPosition()
always returns the last item in the RecyclerView
despite whether they are visible to the user or not. This happens because RecyclerView
placed inside NestedScrollView
behaves like a ListView
without doing any recycling. Meaning all items are visible at the same time because all of them are bind at the same time.
Upvotes: 7