How to center items of a recyclerview?

前端 未结 8 1751
夕颜
夕颜 2020-12-14 14:38

I need to center elements in each row so they will be like in this mockup. I\'ve been searching if there is any layout that works that way without look. items are centered i

8条回答
  •  清歌不尽
    2020-12-14 15:15

    Use the gridLayoutManager = new GridLayoutManager(context,6) and override setSpanSizeLookup.

    Example:

    int totalSize=list.size();
    gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                        @Override
                        public int getSpanSize(int position) {
                            int span;
                            span = totalSize % 3;
                            if (totalSize < 3) {
                                return 6;
                            } else if (span == 0 || (position <= ((totalSize - 1) - span))) {
                                return 2;
                            } else if (span == 1) {
                                return 6;
                            } else {
                                return 3;
                            }
                        }
                    });
    

    This will work if you want to display 3 items in a row and remaining in the center of the grid.

    Change the grid layout manager span counts accordingly your requirement.

提交回复
热议问题