How to add dividers and spaces between items in RecyclerView?

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

    The way how I'm handling the Divider view and also Divider Insets is by adding a RecyclerView extension.

    1.

    Add a new extension file by naming View or RecyclerView:

    RecyclerViewExtension.kt
    

    and add the setDivider extension method inside the RecyclerViewExtension.kt file.

    /*
    * RecyclerViewExtension.kt
    * */
    import androidx.annotation.DrawableRes
    import androidx.core.content.ContextCompat
    import androidx.recyclerview.widget.DividerItemDecoration
    import androidx.recyclerview.widget.RecyclerView
    
    
    fun RecyclerView.setDivider(@DrawableRes drawableRes: Int) {
        val divider = DividerItemDecoration(
            this.context,
            DividerItemDecoration.VERTICAL
        )
        val drawable = ContextCompat.getDrawable(
            this.context,
            drawableRes
        )
        drawable?.let {
            divider.setDrawable(it)
            addItemDecoration(divider)
        }
    }
    

    2.

    Create a Drawable resource file inside of drawable package like recycler_view_divider.xml:

    
    
        
            
            
        
    
    
    

    where you can specify the left and right margin on android:insetLeft and android:insetRight.

    3.

    On your Activity or Fragment where the RecyclerView is initialized, you can set the custom drawable by calling:

    recyclerView.setDivider(R.drawable.recycler_view_divider)
    

    4.

    Cheers

提交回复
热议问题