RecyclerView divider customization

We use the addItemDecoration(ItemDecoration fromHtml) of RecyclerView to create a new class to see what it is

public class CategoryItemDecoration extends RecyclerView.ItemDecoration {
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {

    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        
    }
}

There are two methods: getItemOffsets(). Here I usually specify the offset, that is, the height of the split line, or the position of the drawing, and you always leave a place for me. onDraw() we can draw directly. We can draw anything because there is Canvas, but we usually draw Drawable.

public class CategoryItemDecoration extends RecyclerView.ItemDecoration {
    private Paint mPaint;

    public CategoryItemDecoration(int color) {
        // Draw colors directly for testing purposes only
        mPaint = new Paint();
        mPaint.setColor(color);
        mPaint.setAntiAlias(true);
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int childCount = parent.getChildCount();
        // Get the area to be drawn
        Rect rect = new Rect();
        rect.left = parent.getPaddingLeft();
        rect.right = parent.getWidth() - parent.getPaddingRight();
        for (int i = 0; i < childCount; i++) {
            View childView = parent.getChildAt(i);
            rect.top = childView.getBottom();
            rect.bottom = rect.top + 20;
            // Direct use Canvas To draw a rectangle where it's left out
            c.drawRect(rect, mPaint);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        // In each child View Leave 20 below px To draw a split line
        outRect.bottom += 20;
    }
}

 

2.RecyclerView source code analysis - split line

Conjecture: since the split line is considered, the subview must consider the position left by the split line when measuring. Direct measureChild() method

Guess: the split line will call the drawing method onDraw()

Tags: Android

Posted on Fri, 01 May 2020 11:15:56 -0700 by qadeer_ahmad