这是之前在ListView类中使用divider和dividerHeight参数实现的一个例子:

<ListView
    android:id="@+id/activity_home_list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@android:color/transparent"
    android:dividerHeight="8dp"/>

然而,在RecyclerView类中我没有看到这样的可能性。

<android.support.v7.widget.RecyclerView
    android:id="@+id/activity_home_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical"/>

在这种情况下,是否可以定义边距和/或直接添加自定义分隔符视图到列表项的布局中,或者是否有更好的方法来实现我的目标?


当前回答

2016年10月更新

Android支持库25.0.0版本引入了DividerItemDecoration类:

DividerItemDecoration是一个RecyclerView。ItemDecoration,可以用作LinearLayoutManager的项目之间的分隔符。它支持水平和垂直方向。

用法:

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

以前的回答

有些答案使用的方法已经过时,或者没有给出完整的解决方案,所以我试着做一个简短的、最新的总结。


与ListView不同,RecyclerView类没有任何与分隔符相关的参数。相反,你需要扩展ItemDecoration,一个RecyclerView的内部类:

ItemDecoration允许应用程序向适配器数据集中的特定项视图添加特殊的绘图和布局偏移。这可以用于在项目之间绘制分隔线,高光,视觉分组边界等。 所有itemdecoration都按照它们被添加的顺序绘制,在项目视图之前(在onDraw())和在项目之后(在onDrawOver(Canvas, RecyclerView, RecyclerView. state)。

垂直间距

扩展ItemDecoration,添加一个自定义构造函数,将空格高度作为参数,并覆盖getitemoffset()方法:

public class VerticalSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private final int verticalSpaceHeight;

    public VerticalSpaceItemDecoration(int verticalSpaceHeight) {
        this.verticalSpaceHeight = verticalSpaceHeight;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
            RecyclerView.State state) {
        outRect.bottom = verticalSpaceHeight;
    }
}

如果你不想在最后一项下面插入空格,添加以下条件:

if (parent.getChildAdapterPosition(view) != parent.getAdapter().getItemCount() - 1) {
            outRect.bottom = verticalSpaceHeight;
}

注意:你也可以修改outRect。前,outRect。left和outRect。正确的属性为期望的效果。

分配器ItemDecoration

扩展ItemDecoration并覆盖onDraw()方法:

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

你可以调用第一个构造函数使用默认的Android divider属性,也可以调用第二个构造函数使用你自己的drawable,例如drawable/divide .xml:

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

注意:如果你想在你的项目上绘制分隔线,请重写onDrawOver()方法。

使用

要使用你的新类,添加VerticalSpaceItemDecoration或DividerSpaceItemDecoration到RecyclerView,例如在你的片段的onCreateView()方法中:

private static final int VERTICAL_ITEM_SPACE = 48;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_feed, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.fragment_home_recycler_view);
    linearLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(linearLayoutManager);

    //add ItemDecoration
    recyclerView.addItemDecoration(new VerticalSpaceItemDecoration(VERTICAL_ITEM_SPACE));
    //or
    recyclerView.addItemDecoration(new DividerItemDecoration(getActivity()));
    //or
    recyclerView.addItemDecoration(
            new DividerItemDecoration(getActivity(), R.drawable.divider));

    recyclerView.setAdapter(...);

    return rootView;
}

还有Lucas Rocha的图书馆,旨在简化道具装饰过程。不过我还没试过。

其特点包括:

收藏的库存项目装饰,包括: 项目间距水平/垂直分隔。 列表项

其他回答

2016年10月更新

Android支持库25.0.0版本引入了DividerItemDecoration类:

DividerItemDecoration是一个RecyclerView。ItemDecoration,可以用作LinearLayoutManager的项目之间的分隔符。它支持水平和垂直方向。

用法:

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

以前的回答

有些答案使用的方法已经过时,或者没有给出完整的解决方案,所以我试着做一个简短的、最新的总结。


与ListView不同,RecyclerView类没有任何与分隔符相关的参数。相反,你需要扩展ItemDecoration,一个RecyclerView的内部类:

ItemDecoration允许应用程序向适配器数据集中的特定项视图添加特殊的绘图和布局偏移。这可以用于在项目之间绘制分隔线,高光,视觉分组边界等。 所有itemdecoration都按照它们被添加的顺序绘制,在项目视图之前(在onDraw())和在项目之后(在onDrawOver(Canvas, RecyclerView, RecyclerView. state)。

垂直间距

扩展ItemDecoration,添加一个自定义构造函数,将空格高度作为参数,并覆盖getitemoffset()方法:

public class VerticalSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private final int verticalSpaceHeight;

    public VerticalSpaceItemDecoration(int verticalSpaceHeight) {
        this.verticalSpaceHeight = verticalSpaceHeight;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
            RecyclerView.State state) {
        outRect.bottom = verticalSpaceHeight;
    }
}

如果你不想在最后一项下面插入空格,添加以下条件:

if (parent.getChildAdapterPosition(view) != parent.getAdapter().getItemCount() - 1) {
            outRect.bottom = verticalSpaceHeight;
}

注意:你也可以修改outRect。前,outRect。left和outRect。正确的属性为期望的效果。

分配器ItemDecoration

扩展ItemDecoration并覆盖onDraw()方法:

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

你可以调用第一个构造函数使用默认的Android divider属性,也可以调用第二个构造函数使用你自己的drawable,例如drawable/divide .xml:

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

注意:如果你想在你的项目上绘制分隔线,请重写onDrawOver()方法。

使用

要使用你的新类,添加VerticalSpaceItemDecoration或DividerSpaceItemDecoration到RecyclerView,例如在你的片段的onCreateView()方法中:

private static final int VERTICAL_ITEM_SPACE = 48;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_feed, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.fragment_home_recycler_view);
    linearLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(linearLayoutManager);

    //add ItemDecoration
    recyclerView.addItemDecoration(new VerticalSpaceItemDecoration(VERTICAL_ITEM_SPACE));
    //or
    recyclerView.addItemDecoration(new DividerItemDecoration(getActivity()));
    //or
    recyclerView.addItemDecoration(
            new DividerItemDecoration(getActivity(), R.drawable.divider));

    recyclerView.setAdapter(...);

    return rootView;
}

还有Lucas Rocha的图书馆,旨在简化道具装饰过程。不过我还没试过。

其特点包括:

收藏的库存项目装饰,包括: 项目间距水平/垂直分隔。 列表项

使用这个类在你的RecyclerView中设置分隔符。

public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // Item position
        int column = position % spanCount; // Item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // Top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // Item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = spacing; // Item top
            }
        }
    }
}

因为我已经设置了ItemAnimators。ItemDecorator不会随着动画一起进入或退出。

我只是在我的项目视图布局文件中为每个项目设置了一个视图行。它解决了我的案子。对于一个简单的分割器来说,我觉得它的魔法太多了。

<View
    android:layout_width="match_parent"
    android:layout_height="1px"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:background="@color/lt_gray"/>

我认为使用一个简单的分隔器会对你有帮助

为每个项目添加分隔符:

1. 将其添加到可绘制目录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="#999999" />
</shape>

2. 创建SimpleDividerItemDecoration类

我用这个例子来定义这个类:

https://gist.github.com/polbins/e37206fbc444207c0e92

package com.example.myapp;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.example.myapp.R;

public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration{
    private Drawable mDivider;

    public SimpleDividerItemDecoration(Resources resources) {
        mDivider = resources.getDrawable(R.drawable.line_divider);
    }

    public void onDrawOver(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 + mDivider.getIntrinsicHeight();

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

3.在使用RecyclerView的活动或片段中,在onCreateView中添加以下内容:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
 RecyclerView myRecyclerView = (RecyclerView) layout.findViewById(R.id.my_recycler_view);
 myRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getResources()));
 ....
 }

4. 添加项目之间的间距

你只需要添加padding属性到你的项目视图

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:padding="4dp"
>
..... item structure
</RelativeLayout>

•PrimeAdapter

通过使用PrimeAdapter,在RecyclerViews中处理分隔符可以非常简单。它为创建和管理分隔器提供了多种功能和更大的灵活性。

您可以按以下方式创建适配器(请参阅GitHub中关于使用的完整文档):

val adapter = PrimeAdapter.with(recyclerView)
                    .setLayoutManager(LinearLayoutManager(activity))
                    .set()
                    .build(ActorAdapter::class.java)

创建适配器实例后,您可以简单地使用以下命令添加分隔符:

//----- Default divider:
adapter.setDivider()

//----- Divider with a custom drawable:
adapter.setDivider(ContextCompat.getDrawable(context, R.drawable.divider))

//----- Divider with a custom color:
adapter.setDivider(Color.RED)

//----- Divider with a custom color and a custom inset:
adapter.setDivider(Color.RED, insetLeft = 16, insetRight = 16)

//----- Deactivate dividers:
adapter.setDivider(null)