How to add dividers and spaces between items in RecyclerView?

前端 未结 30 3551
清歌不尽
清歌不尽 2020-11-22 03:27

This is an example of how it could have been done previously in the ListView class, using the divider and dividerHeight parame

30条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 04:11

    Simple ItemDecoration implementation for equal spaces between all items.

    public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
        private int space;
    
        public SpacesItemDecoration(int space) {
            this.space = space;
        }
    
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;
    
            // Add top margin only for the first item to avoid double space between items
            if(parent.getChildAdapterPosition(view) == 0) {
                outRect.top = space;
            }
        }
    }
    

提交回复
热议问题