android – ItemDecoration doesn't work inside NestedScrollView-ThrowExceptions

Exception or error:

I have implemented RecyclerView with sticky headers and I did it through ItemDecoration.
It works as expected in the case of stand-alone recycler view.

<LinearLayout ...>
    <androidx.recyclerview.widget.RecyclerView .../>
    <androidx.recyclerview.widget.RecyclerView ... /> // ItemDecoration is supposed to be here and it works excellent
</LinearLayout>

But I have two lists and I need to use NestedScrollView

<androidx.core.widget.NestedScrollView ...>
<LinearLayout ...>
    <androidx.recyclerview.widget.RecyclerView .../>
    <androidx.recyclerview.widget.RecyclerView ... /> // It doesn't work here
</LinearLayout>
</androidx.core.widget.NestedScrollView ...>

In this case ItemDecoration doesn’t work.

I’ve found out next information:

  • onDrawOver’s are not called on scrolling because RecyclerView.draw() is not called as well.

  • All items are created at same time (so Adapter creates view holders for all items in the data). It’s bad, but it’s not my main problem.

  • I tried to force calling recyclerview’s redraw on scrolling but it doesn’t work

Do you have any advice how to fix it?

UPD xml file:

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:scrollbars="none">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/black_background_color"
        android:focusableInTouchMode="true"
        android:orientation="vertical">
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/menuNewsList"
            android:layout_width="match_parent"
            android:layout_height="170dp" />
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/listMenu"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
    </LinearLayout>
</androidx.core.widget.NestedScrollView>

Code initialization:

listMenu.apply {
    adapter = dishAdapter
    isNestedScrollingEnabled = false
}
listMenu.addItemDecoration(HeaderItemDecoration(listMenu, isHeader = isHeader()))

HeaderItemDecoration was copied from there
How can I make sticky headers in RecyclerView? (Without external lib)

How to solve:

Shouldn’t you add an ItemDecoration to a RecyclerView using the addDecoration(ItemDecoration decoration) method?

Leave a Reply

Your email address will not be published. Required fields are marked *