Using RecyclerView.Adapter, the question arose - how to set up a simple Divider ( Android set divider RecyclerView ) with the possibility of programmatically changing the color and / or thickness for it?
1 answer
I googled a little and experimented a little and got the simplest solution possible.
1) For RecyclerView, it is impossible to just pick up and assign a divider, you must assign it to recyclerView.addItemDecoration()
2) In this connection, I created a descendant class RecyclerView.ItemDecoration and implemented 2 methods - getting the height and the drawing itself.
3)
public class Divider extends RecyclerView.ItemDecoration { private int mColor; private int mHeight; // in px format private Paint mPaint; public Divider(Context ctx, boolean isDarkTheme) { this.mColor = ContextCompat.getColor(ctx, isDarkTheme ? R.color.dark : R.color.light); this.mHeight = 1; //1 px this.mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(mColor); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.set(0, 0, 0, mHeight); //высота разделителя } @Override public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) { for (int i = 0; i < parent.getChildCount(); i++) { View view = parent.getChildAt(i); canvas.drawRect(view.getLeft(), view.getBottom(), view.getRight(), view.getBottom() + mHeight, mPaint); } } } 4) Now, when creating the adapter, we specify the class that is responsible for drawing the separator:
recyclerView.addItemDecoration( new Divider(this,MySystem.getInstance().isDarkTheme()); recyclerView.setAdapter(adapter); I hope this helps you save time when creating editable delimiters for your lists, based on RecyclerView. Good luck!
- A standard
Support Library 25.0.0appeared in theSupport Library 25.0.0so you need to use it developer.android.com/reference/android/support/v7/widget/… - pavel163 - Thanks for expanding the answer, so my solution can be used on everything that uses earlier libraries. For example, my current project uses 23.0.2 - Andrew Grow
- Well yes. But better update the support library. All the same, Google is ruled by bugs in it - pavel163
|