在 RecyclerView 中为分隔线添加边距

Add margins to divider in RecyclerView

我正在构建一个使用 RecyclerView 的 android 应用程序。我想将分隔线添加到 RecyclerView,我使用以下代码做到了这一点:

DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);

到目前为止一切正常。但是,分隔线占用了全屏的大小,我想为其添加边距。有什么方法可以使用一种方法将边距添加到分隔线,该方法将向绘制的矩形添加一些 space,而不是通过创建带有边距的自定义可绘制形状并将其添加到 RecyclerView

使用它并根据您的要求进行自定义。

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};

    private Drawable divider;

    /**
     * Default divider will be used
     */
    public DividerItemDecoration(Context context) {
        final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
        divider = styledAttributes.getDrawable(0);
        styledAttributes.recycle();
    }

    /**
     * Custom divider will be used
     */
    public DividerItemDecoration(Context context, int resId) {
        divider = ContextCompat.getDrawable(context, resId);
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State 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 + divider.getIntrinsicHeight();

            divider.setBounds(left, top, right, bottom);
            divider.draw(c);
        }
    }
}

您可以为回收者视图创建自己的物品装饰。 这是相同的代码。

public class SimpleItemDecorator extends RecyclerView.ItemDecoration {

    int space;
    boolean isHorizontalLayout;
    public SimpleItemDecorator(int space) {
        this.space = space;
    }

    public SimpleItemDecorator(int space, boolean isHorizontalLayout) {
        this.space = space;
        this.isHorizontalLayout = isHorizontalLayout;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        if(isHorizontalLayout)
        {
            outRect.bottom=space;
            outRect.right=space;
            outRect.left=space;
            outRect.top=space;

        } else {
            outRect.bottom = space;
            if (parent.getChildAdapterPosition(view) == 0)
                outRect.top = space;
            else
                outRect.top = 0;

        }


    }
}

要将它与你的 recyclerview 一起使用,你可以这样做:

 recyclerView.addItemDecoration(new SimpleItemDecorator(5));

我认为最直接的解决方案是在 Decoration 对象上使用 setDrawable 方法,并向其传递一个 inset drawable,其中包含您想要的边距 inset 值。像这样:

int[] ATTRS = new int[]{android.R.attr.listDivider};

TypedArray a = context.obtainStyledAttributes(ATTRS);
Drawable divider = a.getDrawable(0);
int inset = getResources().getDimensionPixelSize(R.dimen.your_margin_value);
InsetDrawable insetDivider = new InsetDrawable(divider, inset, 0, inset, 0);
a.recycle();

DividerItemDecoration itemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
itemDecoration.setDrawable(insetDivider);
recyclerView.addItemDecoration(itemDecoration);

与@Vivek 的回答相同,但使用 Kotlin 和不同的参数

class SimpleItemDecorator : RecyclerView.ItemDecoration {

    private var top_bottom: Int = 0
    private var left_right: Int = 0

    /**
     * @param top_bottom for top and bottom margin
     * @param left_right for left and right margin
     */
    constructor(top_bottom: Int, left_right: Int = 0) {
        this.top_bottom = top_bottom
        this.left_right = left_right
    }

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)
        outRect.bottom = top_bottom
        outRect.top = top_bottom
        outRect.right = left_right
        outRect.left = left_right
    }
}

下面是 RecyclerView 中带有左边距的分隔符代码。只需将代码粘贴到 MainActivityOnCreate 方法中即可。

class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;

    public SimpleDividerItemDecoration(Context context) {
        mDivider = context.getResources().getDrawable(R.drawable.divider);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = 250;
        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);
        }
    }
}
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
            getApplicationContext()));

因为 divider.xml 文件将从您的 drawable 文件夹中丢失,所以下面是您在 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="1dp" />

  <solid android:color="@color/divider" />

</shape>

shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#E6E7F0" />
    <size android:height="1dp" />
</shape>

layer.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/shape"
        android:left="16dp"
        android:right="16dp" />

</layer-list>

代码

val itemDecoration = DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
itemDecoration.setDrawable(resources.getDrawable(R.drawable.layer, null))
recyclerView.addItemDecoration(itemDecoration)

详述@SeptimusX75:如果您(像我一样)喜欢在 XML 中做 UI 事情,您可以创建一个插图可绘制文件。您必须创建第二个 XML 文件,但由于在 return 中您的代码变得更清晰,我认为这是值得的 :-)。

[UPDATE] 作为用户@Zhou Hongbo 在评论中建议,仅使用一个XML 文件:divider.xml:

<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/divider_base"
    android:insetRight="20dp"
    android:insetLeft="20dp">

    <shape>
        <android:shape="rectangle">
        <size android:height="1dp" />
        <solid android:color="@color/dividerColor" />
    </shape>

</inset>

[旧答案]:

divider_base.xml (实际分频器):

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size android:height="1dp" />
    <solid android:color="@color/dividerColor" />
</shape>

divider.xml (插图):

<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/divider_base"
    android:insetRight="20dp"
    android:insetLeft="20dp">
</inset>

这是一个简单的 Kotlin 代码片段,用于使用 RecyclerView 实现 ItemDecoration:

 recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                    outRect.left = 20    // Left Margin.
                    outRect.right = 20   // Right Margin.
                    outRect.top = 16     // Top Margin.
                    outRect.bottom = 16  // Bottom Margin.
                }
            })

说明:- 在上面的示例代码中,我们为每个项目添加边距 四个方向的 RecyclerView。

编码愉快...

我找到了最好最简单的解决方案

<inset xmlns:android="http://schemas.android.com/apk/res/android"
       android:insetLeft="40dp"
       android:insetRight="40dp" >
    <shape>
        <size android:height="1dp"/>
        <solid android:color="@color/recyclerview_divider" />
    </shape>
</inset>

发件人: