Android 将分隔器添加到RecyclerView

示例

首先,您需要创建一个扩展类RecyclerView.ItemDecoration:

public class SimpleBlueDivider extendsRecyclerView.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.Statestate) {
    //分隔符填充可根据需要或禁用任何填充
    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.LayoutParamsparams = (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到您的可绘制文件夹中:

<?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));

结果将如下所示:

该图像只是分隔器如何工作的一个示例,如果要在添加分隔器时遵循材料设计规范,请查看以下链接:分隔器,并通过提供链接感谢@Brenden Kromhout。