Margin/padding in last Child in RecyclerView

前端 未结 9 993
醉话见心
醉话见心 2021-01-30 05:56

I\'m trying to add Padding/Margin Bottom in the last row and Padding/Margin Top in the first row. I can not do it in the item xml as it would affect all of my Children.

I

9条回答
  •  悲哀的现实
    2021-01-30 06:25

    I have modified amazing answer @snachmsm answer for better and give you idea how to use properly

    public class SpacesItemDecoration extends DividerItemDecoration {
        private int space;
    
        public SpacesItemDecoration(Context clContext,int oriantation,int space) {
            super(clContext,oriantation);
            this.space = space;
        }
    
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect,view,parent,state);
            int position = parent.getChildAdapterPosition(view);
            boolean isLast = position == state.getItemCount()-1;
            if(isLast){
                outRect.bottom = space;
                outRect.top = 0; //don't forget about recycling...
            }
           /* if(position == 0){
                outRect.top = space;
                // don't recycle bottom if first item is also last
                // should keep bottom padding set above
                if(!isLast)
                    outRect.bottom = 0;
            }*/
        }
    }
    

提交回复
热议问题