Home » Android » android recyclerview removing all items conflicts with item decoration of first item-Exceptionshub

android recyclerview removing all items conflicts with item decoration of first item-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

in order to remove all items from recyclerview, I’m using the below code:

    int size = recyclerViewAdapter.getItemCount();
    recyclerViewAdapter.clearList();
    recyclerViewAdapter.notifyItemRangeRemoved(0, size);

the recycler view is using the following ItemDecoration:

public class CollectionsDecoration extends RecyclerView.ItemDecoration {
    private int margin;

    public CollectionsDecoration(Context context) {
        margin = MeasurementsComputer.getPX(5, context);
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        outRect.left = 0;
        outRect.right = 0;
        outRect.bottom = 0;
        if (parent.getChildAdapterPosition(view) == 0)
            outRect.top = 15 * margin;
        else
            outRect.top = 0;
    }
}

as you can see, the first item has a larger top margin. the problem is that when I run the above code to remove all items, all items including the first item gets the top margin of zero, and then they get removed and hided. why the item decoration of first item is not respected at the time of removing?

How to&Answers:

If I understand correctly, you want to keep item decoration when you remove all items?
In that case, you can try adding separate view on top, and when the list is empty, set its visibility to View.VISIBLE, and when the list is not empty, set it to View.INVISIBLE.

Example of custom view as a decorator:


    <View
            android:id="@+id/dividerView"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#E3E4E5" />