Draw multiple lines on a RecyclerView background

末鹿安然 提交于 2019-12-13 21:18:11

问题


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


回答1:


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));


来源:https://stackoverflow.com/questions/36682435/draw-multiple-lines-on-a-recyclerview-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!