在 RecyclerView 背景上绘制多条线

Draw multiple lines on a RecyclerView background

我正在尝试在 RecyclerView 背景上绘制多条水平线。 这些线必须位于精确的位置,因为它们之间必须有一个元素列表。我可以将线条添加到每个元素,但我需要绘制这些线条,即使没有元素添加到列表中也是如此。

如何在背景上画线? (我无法从 .xml 开始)感谢您的宝贵时间!

Example image

您似乎想要绘制列表分隔符。我想你想使用 ItemDecoration

在编写装饰器时,您要确保考虑到 translationY(处理项目 add/remove 动画)和其他装饰的项目偏移量(例如 layoutManager.getDecoratedBottom(view))

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

    private Drawable mDivider;

    public DividerItemDecoration(Context context) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getLeft();
        int right = parent.getRight();
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();

        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            int ty = (int) (child.getTranslationY() + 0.5f);
            int top = layoutManager.getDecoratedBottom(child) + ty;
            int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
}


recyclerView.addItemDecoration(new DividerItemDecoration(context));