How to add a divider between each grid of Recycler

2019-09-07 04:28发布

问题:

I need to add a divider between each grid of the 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);

Please help me.

Example:

回答1:

You need Decoration for this.
Here is the example:

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

And in your activity/fragment

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


回答2:

I think, that Jagadesh Seeram was talking about horizontal divider between items, but RecyclerView.ItemDecoration adds divider everywhere.

If you don't use autoscroll to some item, you should write like this:

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

}