Add margins to divider in RecyclerView

后端 未结 8 883
深忆病人
深忆病人 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:37

    I think the most straightforward solution is to use the setDrawable method on the Decoration object and pass it an inset drawable with the inset values you want for the margins. Like so:

    int[] ATTRS = new int[]{android.R.attr.listDivider};
    
    TypedArray a = context.obtainStyledAttributes(ATTRS);
    Drawable divider = a.getDrawable(0);
    int inset = getResources().getDimensionPixelSize(R.dimen.your_margin_value);
    InsetDrawable insetDivider = new InsetDrawable(divider, inset, 0, inset, 0);
    a.recycle();
    
    DividerItemDecoration itemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
    itemDecoration.setDrawable(insetDivider);
    recyclerView.addItemDecoration(itemDecoration);
    
    0 讨论(0)
  • 2020-12-14 01:42

    Same like @Vivek answer but in Kotlin and different params

    class SimpleItemDecorator : RecyclerView.ItemDecoration {
    
        private var top_bottom: Int = 0
        private var left_right: Int = 0
    
        /**
         * @param top_bottom for top and bottom margin
         * @param left_right for left and right margin
         */
        constructor(top_bottom: Int, left_right: Int = 0) {
            this.top_bottom = top_bottom
            this.left_right = left_right
        }
    
        override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
            super.getItemOffsets(outRect, view, parent, state)
            outRect.bottom = top_bottom
            outRect.top = top_bottom
            outRect.right = left_right
            outRect.left = left_right
        }
    }
    
    0 讨论(0)
提交回复
热议问题