Skip to content

Instantly share code, notes, and snippets.

@Leaking
Last active May 5, 2020 20:33
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Leaking/3e69ee94a278abe16f10 to your computer and use it in GitHub Desktop.
Save Leaking/3e69ee94a278abe16f10 to your computer and use it in GitHub Desktop.
A simple RecyclerView ItemDecoration drawing a horizon line and you can set the height and the color.It looks like the listview divider.
package com.quinn.xmpp.ui.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.quinn.xmpp.R;
public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
private int mColor;
private int mHeight; // in px format
private Paint paint;
public SimpleDividerItemDecoration(Context context, int color, int height) {
this.mColor = color;
this.mHeight = height;
this.paint = new Paint();
paint.setAntiAlias(true);
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mHeight;
paint.setColor(mColor);
c.drawRect(left, top, right, bottom, paint);
}
}
}
@tiagomartinho
Copy link

tiagomartinho commented Oct 15, 2018

Kotlin version:

import android.graphics.Canvas
import android.graphics.Paint
import android.support.v7.widget.RecyclerView

class SimpleDividerItemDecoration(
    private val color: Int, private val height: Int
) : RecyclerView.ItemDecoration() {

    private val paint = Paint()

    init {
        paint.isAntiAlias = true
    }

    override fun onDrawOver(c: Canvas, parent: RecyclerView) {
        val left = parent.paddingLeft
        val right = parent.width - parent.paddingRight

        val childCount = parent.childCount
        for (i in 0 until childCount) {
            val child = parent.getChildAt(i)

            val params = child
                .layoutParams as RecyclerView.LayoutParams

            val top = child.bottom + params.bottomMargin
            val bottom = top + height

            paint.color = color
            c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paint)
        }
    }
}

@nivekmai
Copy link

nivekmai commented May 5, 2020

You'll also want to extend the itemOffset to fit the drawn rectangle, or else you'll be drawing on top of your views: https://gist.github.com/nivekmai/7b9d20629a22f7ada87c849ed9dcbc32

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment