How to add a divider between each grid of RecyclerView?

假装没事ソ 提交于 2019-12-13 06:07:52

问题


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

}


来源:https://stackoverflow.com/questions/32654844/how-to-add-a-divider-between-each-grid-of-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!