How to make RecyclerView recycle inside NestedScrollView?

I tried to put several views, including RecyclerView, in NestedScrollView. I used setNestedScrollingEnabled(false)and it looked nice for small datasets, but became more frequent for large ones.

After spending some time registering the method onCreateViewHolder(), I realized that the recycler view creates them all at once as old ListView. I tried to find the reasons for this behavior in RecyclerViewdocs, but found it in ScrollView description :

You should never use ScrollView with ListView because ListView takes care of its own vertical scrolling. Most importantly, by doing this it strikes all the important optimizations in ListView for working with large lists, since it effectively forces the ListView to display its entire list of items to fill the infinite container delivered by ScrollView.

I was hoping it NestedScrollViewwould solve the problem, but it does not seem to have happened.

Are there any ways, for example, using some custom one to LayoutManageruse RecyclerViewwith its viewing utilization optimization?

Ps Of course, I know about the method getItemViewType(int pos)and the ability to add custom headers and footers using this technique, but it looks like an ugly workaround for me. And yes, I'm using it at the moment, because it's better to have code that is harder to maintain than such a big performance issue.

+4
source share
1 answer

You need to change your layout as shown below. You use NestedScrollViewwhat you need to add the property android:nestedScrollingEnabledtoRecyclerView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/YOUR_NEESTED_SCROLLVIEW"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/YOUR_RECYCLVIEW"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:nestedScrollingEnabled="false" />

    </android.support.v4.widget.NestedScrollView>
</LinearLayout>
+1
source

Source: https://habr.com/ru/post/1672230/


All Articles