You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android中如何为RecyclerView项间分割线添加上下边距?

How to Add Custom Margins to a Custom RecyclerView DividerItemDecoration

Great question! Adding custom margins to your RecyclerView divider is straightforward—you just need to adjust how you calculate the divider's bounds in your DividerItemDecorator class, or use a wrapped drawable if you prefer a XML-only approach. Let's walk through both options.

This approach lets you pass custom margin values when initializing the decorator, so you can adjust margins dynamically for different use cases.

First, update your DividerItemDecorator to accept margin parameters and use them to calculate the divider's drawable bounds:

class DividerItemDecorator(
    private val mDivider: Drawable,
    private val leftMargin: Int = 0,
    private val topMargin: Int = 0,
    private val rightMargin: Int = 0,
    private val bottomMargin: Int = 0
) : RecyclerView.ItemDecoration() {

    override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        // Adjust left/right bounds with custom margins
        val dividerLeft = parent.paddingLeft + leftMargin
        val dividerRight = parent.width - parent.paddingRight - rightMargin
        
        val childCount = parent.childCount
        for (i in 0..childCount - 2) {
            val child: View = parent.getChildAt(i)
            val params = child.layoutParams as RecyclerView.LayoutParams
            
            // Adjust top/bottom bounds with custom margins
            val dividerTop: Int = child.bottom + params.bottomMargin + topMargin
            val dividerBottom = dividerTop + mDivider.intrinsicHeight + bottomMargin
            
            mDivider.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom)
            mDivider.draw(canvas)
        }
    }
}

Next, convert dp values to pixels (since Android uses pixels for layout calculations) and initialize the decorator with your desired margins. Add a helper method for conversion, then set up the divider:

// Helper to convert dp to pixels
fun dpToPx(context: Context, dp: Int): Int {
    return (dp * context.resources.displayMetrics.density).toInt()
}

// Initialize the divider with custom margins (example: 20dp left/right, 5dp top/bottom)
val context = itemView.context
val divider = DividerItemDecorator(
    mDivider = ContextCompat.getDrawable(context, R.drawable.recyclerview_divider)!!,
    leftMargin = dpToPx(context, 20),
    topMargin = dpToPx(context, 5),
    rightMargin = dpToPx(context, 20),
    bottomMargin = dpToPx(context, 5)
)

subNodeBody.addItemDecoration(divider)
subNodeBody.adapter = RolesAdapter(subNode.roles)

Finally, clean up your recyclerview_divider.xml—the width size is unnecessary now since we're controlling the divider's width via code:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="#e7eef3"/>
    <size android:height="0.7dp"/>
</shape>

Option 2: Use InsetDrawable (XML-Only, Static Margins)

If you don't need dynamic margins, you can wrap your divider shape in an <inset> drawable to add padding directly in XML:

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="20dp"
    android:insetTop="5dp"
    android:insetRight="20dp"
    android:insetBottom="5dp">
    
    <shape android:shape="rectangle">
        <solid android:color="#e7eef3"/>
        <size android:height="0.7dp"/>
    </shape>
</inset>

Then just use this new drawable when initializing your original DividerItemDecorator—no code changes needed! The downside here is margins are fixed in the drawable, so you can't adjust them at runtime without creating multiple drawable files.

Key Notes

  • The first option is better for apps where you might need different margins in different RecyclerViews, or if you want to adjust margins dynamically.
  • Always convert dp to pixels when working with layout values in code to ensure consistency across different screen densities.

内容的提问来源于stack exchange,提问作者Rahul

火山引擎 最新活动