Created
August 22, 2015 23:22
-
-
Save rlac/de3607309d6ae03912d1 to your computer and use it in GitHub Desktop.
RecyclerView ItemDecorator to add dividers to vertical LinearLayoutManager items
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.content.res.TypedArray; | |
import android.graphics.Canvas; | |
import android.graphics.Rect; | |
import android.graphics.drawable.Drawable; | |
import android.support.v7.widget.RecyclerView; | |
import android.view.View; | |
public class ItemDividerDecoration extends RecyclerView.ItemDecoration { | |
private final Drawable divider; | |
public ItemDividerDecoration(Context context) { | |
final TypedArray a = context.obtainStyledAttributes(new int[]{ android.R.attr.listDivider }); | |
divider = a.getDrawable(0); | |
a.recycle(); | |
} | |
@Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { | |
final int left = parent.getPaddingLeft(); | |
final int right = parent.getWidth() - parent.getPaddingRight(); | |
final int childCount = parent.getChildCount(); | |
for (int idx = 0; idx < childCount; idx++) { | |
View view = parent.getChildAt(idx); | |
if (shouldDraw(parent, view)) { | |
RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams(); | |
final int top = view.getBottom() + lp.bottomMargin; | |
final int bottom = top + divider.getIntrinsicHeight(); | |
divider.setBounds(left, top, right, bottom); | |
divider.draw(c); | |
} | |
} | |
} | |
@Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { | |
if (shouldDraw(parent, view)) { | |
outRect.bottom = divider.getIntrinsicHeight(); | |
} else { | |
super.getItemOffsets(outRect, view, parent, state); | |
} | |
} | |
protected boolean shouldDraw(RecyclerView parent, View view) { | |
return !isLast(parent, view); | |
} | |
protected boolean isLast(RecyclerView parent, View view) { | |
return parent.getChildAdapterPosition(view) == parent.getAdapter().getItemCount() - 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment