How to add dividers and spaces between items in RecyclerView?

前端 未结 30 3367
清歌不尽
清歌不尽 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:34

    I feel like there's a need for a simple, code-based answer that doesn't use XML

    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL);
    
    ShapeDrawable shapeDrawableForDivider = new ShapeDrawable(new RectShape());
    
    int dividerThickness = // (int) (SomeOtherView.getHeight() * desiredPercent);
    shapeDrawableForDivider.setIntrinsicHeight(dividerThickness);
    shapeDrawableForDivider.setAlpha(0);
    
    dividerItemDecoration.setDrawable(shapeDrawableForDivider);
    
    recyclerView.addItemDecoration(dividerItemDecoration);
    

    I love this answer so much, I re-wrote it in a single-expression Kotlin answer:

        recyclerView.addItemDecoration(DividerItemDecoration(this,DividerItemDecoration.VERTICAL).also { deco ->
            with (ShapeDrawable(RectShape())){
                intrinsicHeight = (resources.displayMetrics.density * 24).toInt()
                alpha = 0
                deco.setDrawable(this)
            }
        })
    

    This does the same thing as @Nerdy's original answer, except it sets the height of the divider to 24dp instead of a percentage of another view's height.

提交回复
热议问题