在RecyclerView背景上绘制多条线

时间:2016-04-17 21:26:43

标签: android android-recyclerview android-background

我试图在RecyclerView背景上绘制多条水平线。 这些线必须处于精确位置,因为有一系列元素必须适合它们。我可以将线条添加到每个元素,但我需要绘制这些线条,即使列表中没有添加任何元素。

如何在背景上画线? (我不能用.xml来做)谢谢你的时间!

Example image

1 个答案:

答案 0 :(得分:0)

看起来你想绘制列表分隔符。我想你想用ItemDecoration

在编写装饰器时,您要确保考虑翻译(处理项目添加/删除动画)和其他装饰的项目偏移(例如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));