将分隔符添加到 RecyclerView
首先,你需要创建一个扩展 RecyclerView.ItemDecoration
的类:
public class SimpleBlueDivider extends RecyclerView.ItemDecoration {
private Drawable mDivider;
public SimpleBlueDivider(Context context) {
mDivider = context.getResources().getDrawable(R.drawable.divider_blue);
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
//divider padding give some padding whatever u want or disable
int left =parent.getPaddingLeft()+80;
int right = parent.getWidth() - parent.getPaddingRight()-30;
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);
}
}
}
将 divider_blue.xml
添加到你的 drawable 文件夹:
<?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="4dp" />
<solid android:color="#AA123456" />
</shape>
然后使用它像:
recyclerView.addItemDecoration(new SimpleBlueDivider(context));
结果如下:
这个图像只是分频器如何工作的一个例子,如果你想在添加分频器时遵循 Material Design 规范,请看一下这个链接: 分频器并通过提供链接感谢 @Brenden Kromhout 。