RecyclerView remove divider / decorator after the last item

前端 未结 9 2119
礼貌的吻别
礼貌的吻别 2020-12-07 17:46

I have a quite simple RecyclerView.
This is how I set the divider:

DividerItemDecoration itemDecorator = new DividerItemDecoration(getContext(), DividerI         


        
9条回答
  •  甜味超标
    2020-12-07 17:50

    The accepted answer doesn't allocate space for decoration as it does not override getItemOffsets()

    I have tweaked the DividerItemDecoration from support library to exclude the decoration from the last item

    public class DividerItemDecorator extends RecyclerView.ItemDecoration {
    
        private Drawable mDivider;
        private final Rect mBounds = new Rect();
    
        public DividerItemDecorator(Drawable divider) {
            mDivider = divider;
        }
    
        @Override
        public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
            canvas.save();
            final int left;
            final int right;
            if (parent.getClipToPadding()) {
                left = parent.getPaddingLeft();
                right = parent.getWidth() - parent.getPaddingRight();
                canvas.clipRect(left, parent.getPaddingTop(), right,
                        parent.getHeight() - parent.getPaddingBottom());
            } else {
                left = 0;
                right = parent.getWidth();
            }
    
            final int childCount = parent.getChildCount();
            for (int i = 0; i < childCount - 1; i++) {
                final View child = parent.getChildAt(i);
                parent.getDecoratedBoundsWithMargins(child, mBounds);
                final int bottom = mBounds.bottom + Math.round(child.getTranslationY());
                final int top = bottom - mDivider.getIntrinsicHeight();
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            }
            canvas.restore();
        }
    
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    
            if (parent.getChildAdapterPosition(view) == state.getItemCount() - 1) {
                outRect.setEmpty();
            } else
                outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        }
    }
    

    To apply the decorator, use

    RecyclerView.ItemDecoration dividerItemDecoration = new DividerItemDecorator(dividerDrawable);
    recyclerView.addItemDecoration(dividerItemDecoration);
    

    The source for including orientation can be found here https://gist.github.com/abdulalin/146f8ca42aa8322692b15663b8d508ff

提交回复
热议问题