如何在RecyclerView的每个网格之间添加分隔符?

时间:2015-09-18 14:45:51

标签: android android-recyclerview divider

我需要在RecyclerView的每个网格之间添加一个分隔符。

RecyclerView recyclerView= (RecyclerView) profileView.findViewById(R.id.profile_recycler_view);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
Adapter Adapter = new Adapter(getActivity());
recyclerView.setAdapter(profileAdapter);

请帮帮我。

实施例

Example

2 个答案:

答案 0 :(得分:4)

您需要Decoration
这是一个例子:

public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
    private int offset;

    public ItemOffsetDecoration(int offset) {
        this.offset = offset;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.left = offset;
        outRect.right = offset;
        outRect.bottom = offset;
        if(parent.getChildAdapterPosition(view) == 0) {
            outRect.top = offset;
        }
    }
}

在你的活动/片段中

grid.setLayoutManager(new GridLayoutManager(this, 2));
grid.addItemDecoration(new ItemOffsetDecoration(1));

答案 1 :(得分:1)

我认为,Jagadesh Seeram谈论的是项目之间的水平分隔,但RecyclerView.ItemDecoration在任何地方都添加了分隔符。

如果您不使用自动滚动到某个项目,您应该这样写:

public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
private int offset;

public ItemOffsetDecoration(int offset) {
    this.offset = offset;
}

@Override
public void getItemOffsets(Rect outRect, View view,
                           RecyclerView parent, RecyclerView.State state) {
    int bottonIndex;
    if (parent.getAdapter().getItemCount() % 2 == 0){
        bottonIndex = parent.getAdapter().getItemCount() - 2;
    } else {
        bottonIndex = parent.getAdapter().getItemCount() - 1;
    }

    if (parent.getChildAdapterPosition(view) < bottonIndex){
        outRect.bottom = offset;
    } else {
        outRect.bottom = 0;
    }

    if(parent.getChildAdapterPosition(view) > 1 ) {
        outRect.top = offset;
    } else {
        outRect.top = 0;
    }

    if( (parent.getChildAdapterPosition(view) % 2 ) == 0) {
        outRect.right = offset;
        outRect.left = 0;
    } else {
        outRect.right = 0;
        outRect.left = offset;
    }

}