这是之前在ListView类中使用divider和dividerHeight参数实现的一个例子:

<ListView
    android:id="@+id/activity_home_list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@android:color/transparent"
    android:dividerHeight="8dp"/>

然而,在RecyclerView类中我没有看到这样的可能性。

<android.support.v7.widget.RecyclerView
    android:id="@+id/activity_home_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical"/>

在这种情况下,是否可以定义边距和/或直接添加自定义分隔符视图到列表项的布局中,或者是否有更好的方法来实现我的目标?


当前回答

我觉得需要一个简单的、不使用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);

我非常喜欢这个答案,我用Kotlin的单一表达式重新写了一遍:

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

这和@Nerdy最初的答案是一样的,只是它将分隔线的高度设置为24dp,而不是另一个视图高度的百分比。

其他回答

public class VerticalItemDecoration extends RecyclerView.ItemDecoration {

    private boolean verticalOrientation = true;
    private int space = 10;

    public VerticalItemDecoration(int value, boolean verticalOrientation) {
        this.space = value;
        this.verticalOrientation = verticalOrientation;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                               RecyclerView.State state) {
        // Skip first item in the list
        if (parent.getChildAdapterPosition(view) != 0) {
            if (verticalOrientation) {
                outRect.set(space, 0, 0, 0);
            } else if (!verticalOrientation) {
                outRect.set(0, space, 0, 0);
            }
        }
    }
}

mCompletedShippingRecyclerView.addItemDecoration(new VerticalItemDecoration(20,false));

2016年10月更新

在v25.0.0支持库中,终于有了基本水平和垂直分隔符的默认实现!

DividerItemDecoration

最新的方法是这样的,例如在Fragment的onCreateView中使用:

        val recyclerView = rootView.findViewById<RecyclerView>(R.id.recycler_view)
        recyclerView.adapter = mListAdapter
        recyclerView.layoutManager = LinearLayoutManager(context)
        rootView.context.let {
            val dividerItemDecoration = MaterialDividerItemDecoration(
                it,
                MaterialDividerItemDecoration.VERTICAL
            )
            dividerItemDecoration.isLastItemDecorated = false

            // https://github.com/material-components/material-components-android/blob/master/docs/components/Divider.md
            // Needed if you did not set colorOnSurface in your theme because otherwise the default color would be pink_900 -> default according to Material should be colorOnSurface (12% opacity applied automatically on top).
//            dividerItemDecoration.setDividerColorResource(it, R.color.colorDivider)

            recyclerView.addItemDecoration(dividerItemDecoration)
        }

我想你们可以忘记之前所有的解。

使用RecyclerView itemdecoration -一个基本的分隔符样本在Kotlin android

一个完整的示例,包括一个构建器,添加边缘或使用资源颜色的可能性

    class SeparatorDecoration constructor(ctx: Context, @ColorRes dividerColor: Int, heightDp: Float) :
    RecyclerView.ItemDecoration() {

    private val mPaints = Paint()

    init {
        mPaints.color = dividerColor
        val thickness = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            heightDp,
            ctx.resources.displayMetrics
        )
        mPaints.strokeWidth = thickness
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val params = view.layoutParams as RecyclerView.LayoutParams

        // and add a separator to any view but the last one
        val p = params.viewAdapterPosition

        // and add a separator to any view but the last one
        if (p < state.itemCount) outRect[0, 0, 0] =
            mPaints.strokeWidth.toInt() // left, top, right, bottom
        else outRect.setEmpty() // 0, 0, 0, 0
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {

        // we set the stroke width before, so as to correctly draw the line we have to offset by width / 2
        val offset = (mPaints.strokeWidth / 2).roundToInt()

        // this will iterate over every visible view
        for (i in 0 until parent.childCount) {
            // get the view
            val view: View = parent.getChildAt(i)
            val params = view.layoutParams as RecyclerView.LayoutParams

            // get the position
            val position = params.viewAdapterPosition

            // and finally draw the separator
            if (position < state.itemCount) {
                c.drawLine(
                    view.left.toFloat(),
                    (view.bottom + offset).toFloat(),
                    view.right.toFloat(), (view.bottom + offset).toFloat(), mPaints
                )
            }
        }
    }
  }

设置很简单。只需将您的装饰与其余的初始设置一起添加到您的recyclerView。

 val decoration = SeparatorDecoration(context, R.color.primaryColor, 1.5f)
 recyclerview.addItemDecoration(decoration)

我从一个旧的要点中分叉了DividerItemDecoration,并简化了它以适应我的用例,我还修改了它,以在ListView中绘制的方式绘制分隔符,包括在最后一个列表项之后的分隔符。这也会处理垂直的ItemAnimator动画:

1)将这个类添加到你的项目中:

public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
    private Drawable divider;

    public DividerItemDecoration(Context context) {
        try {
            final TypedArray a = context.obtainStyledAttributes(ATTRS);
            divider = a.getDrawable(0);
            a.recycle();
        } catch (Resources.NotFoundException e) {
            // TODO Log or handle as necessary.
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        if (divider == null) return;
        if (parent.getChildAdapterPosition(view) < 1) return;

        if (getOrientation(parent) == LinearLayoutManager.VERTICAL)
            outRect.top = divider.getIntrinsicHeight();
        else
            throw new IllegalArgumentException("Only usable with vertical lists");
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        if (divider == null) {
            super.onDrawOver(c, parent, state);
            return;
        }

        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();
        final int childCount = parent.getChildCount();

        for (int i = 0; i < childCount; ++i) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int size = divider.getIntrinsicHeight();
            final int top = (int) (child.getTop() - params.topMargin - size + child.getTranslationY());
            final int bottom = top + size;
            divider.setBounds(left, top, right, bottom);
            divider.draw(c);

            if (i == childCount - 1) {
                final int newTop = (int) (child.getBottom() + params.bottomMargin + child.getTranslationY());
                final int newBottom = newTop + size;
                divider.setBounds(left, newTop, right, newBottom);
                divider.draw(c);
            }
        }
    }

    private int getOrientation(RecyclerView parent) {
        if (!(parent.getLayoutManager() instanceof LinearLayoutManager))
            throw new IllegalStateException("Layout manager must be an instance of LinearLayoutManager");
        return ((LinearLayoutManager) parent.getLayoutManager()).getOrientation();
    }
}

2)添加装饰器到你的RecylerView:

recyclerView.addItemDecoration(new DividerItemDecoration(getActivity()));