Add ItemDecoration for the RecyclerView Android
That why, if i want to add the line blow item we show do the below step:
- Create CustomDividerItemDecoration.java
- Create line_divider.xml
- Add CustomDividerItemDecoration.java into MainActivity.java
public class CustomDividerItemDecoration extends RecyclerView.ItemDecoration { private Drawable mDivider; public CustomDividerItemDecoration(Context context){ //mDivider = context.getResources() // .getDrawable(R.drawable.line_divider); //deprecated mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDraw(c, parent, state); 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 + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } }Create line_divider.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <size android:width="1dp" android:height="1dp"/> <solid android:color="#ff0000"/> </shape>Add CustomDividerItemDecoration.java into MainActivity.java
mRecyclerView.addItemDecoration(new CustomDividerItemDecoration(this));Output
Comments
Post a Comment