Add margins to divider in RecyclerView

后端 未结 8 937
深忆病人
深忆病人 2020-12-14 01:11

i am building an android app which is using RecyclerView. I want to add dividers to RecyclerView, which I did using this code:

Divi         


        
8条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 01:24

    You can create your own item decoration for recycler view. Here is code for the same.

    public class SimpleItemDecorator extends RecyclerView.ItemDecoration {
    
        int space;
        boolean isHorizontalLayout;
        public SimpleItemDecorator(int space) {
            this.space = space;
        }
    
        public SimpleItemDecorator(int space, boolean isHorizontalLayout) {
            this.space = space;
            this.isHorizontalLayout = isHorizontalLayout;
        }
    
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            if(isHorizontalLayout)
            {
                outRect.bottom=space;
                outRect.right=space;
                outRect.left=space;
                outRect.top=space;
    
            } else {
                outRect.bottom = space;
                if (parent.getChildAdapterPosition(view) == 0)
                    outRect.top = space;
                else
                    outRect.top = 0;
    
            }
    
    
        }
    }
    

    And to use it with your recyclerview you can do like this:

     recyclerView.addItemDecoration(new SimpleItemDecorator(5));
    

提交回复
热议问题