0

I'm trying to draw multiple horizontal lines on a RecyclerView background. These lines have to be at a precise position, because there is a list of elements which have to fit between them. I could just add the lines to each element but I need those lines drawn, even if there are no elements added to the list.

How can I draw lines on the background? (I can't do it from the .xml) Thank you for your time!

Example image

Eenvincible
  • 5,641
  • 2
  • 27
  • 46
Starivore
  • 279
  • 1
  • 13

1 Answers1

0

It looks like you want to draw list dividers. I think you want to use ItemDecoration

When writing a decorator you want to make sure you account for translationY (handles item add/remove animation) and item offsets from other decorations (e.g. 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));
cyroxis
  • 3,661
  • 22
  • 37
  • works like a charm! but i need to have all the drawn lines displayed even if i don't have all the recycleview elements created. I basicaly need to mimic a notepad page. How can i do that, maintaining the recycleview list? thank you for your time! – Starivore Apr 20 '16 at 11:58
  • You would need to add a second loop after the first that continues drawing dividers until bottom >= parent.bottom(); – cyroxis Apr 20 '16 at 12:17
  • Thank you it worked with bottom <= parent.getBottom! – Starivore Apr 20 '16 at 20:39