martinseal1987
martinseal1987

Reputation: 2428

Reset Recycler view decoration with diff utils

I have a grid recycler view that I update using diff utils, but if something in the list data causes an item to go from any row below the first row, up to the first row then the decoration lacks padding top, this is kind of expected as I'm only adding padding to the top of an item in the list if it is in the first row. I then add bottom padding to every item,

Recycler View Decoration

    public class GridSpacing extends RecyclerView.ItemDecoration {
        private final int spacing;
        private final int numColumns;

        public  GridSpacing(int spacing, int numColumns) {
            this.spacing = spacing;
            this.numColumns = numColumns;
        }

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

            int position = parent.getChildLayoutPosition(view);

            if (position < numColumns){
                outRect.top = spacing;
            }

            if (position % 2 != 0) {
                outRect.right = spacing;
            }

            outRect.left = spacing;
            outRect.bottom = spacing;

        }
    }

If I call notifyDatasetChanged, this will recalculate my decoration and add the padding to the top row, but diff utils is not calling notifyDatasetChanged (think it calls a combination of item range changed, item inserted, item removed, to keep animations) so my decoration doesn't get reapplied, I could probably reapply it myself but that seems like a hack to have to remove and reapply the decoration every time an item changes, does anyone know of a better approach?

Upvotes: 2

Views: 689

Answers (1)

martinseal1987
martinseal1987

Reputation: 2428

so instead of trying to reapply the decorator I'm going to remove the padding top in the decorator and instead add padding to the top and clip to padding false on the recycler view

  <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="8dp"
        android:clipToPadding="false"
        android:id="@+id/recyclerView"/>

Upvotes: 1

Related Questions