使用 GridLayoutManager 为每一行设置不同的跨度

set different span for a every row with GridLayoutManager

我想为 GridLayoutManager 的每一行设置不同的跨度。

 GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        gridView.setLayoutManager(gridLayoutManager);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {

                Log.e("SPAN",position%3+" <=="+position);
                switch (position % 3) {
                    case 1:
                        return 1;

                    case 2:
                        return 2;

                    case 0:
                        return 3;

                    default:return 3;
                }
            }
        });

以上代码集如下(这里imageview作为一个item)

int previousValue = 0;    
SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
                override int  getSpanSize(position){
                    if (position == 0) {
                        previousValue = 6;
                        return previousValue ;
                    }else
                    if (previousValue == 6) {
                        previousValue =3;
                        return previousValue ;
                    } else if(previousValue == 3){
                       previousValue =2;
                       return previousValue ;
                }else if(previousValue ==2){
                      previousValue  = 6;
                      return previousValue ;
                     }
            }
            GridLayoutManager glm = new GridLayoutManager(this, 6)

            glm.spanSizeLookup = spanSizeLookup;
            recycler_view.setLayoutManager(glm)

你的逻辑好像有问题。尝试以下逻辑:

    gridLayoutManager.setSpanSizeLookup(new GgridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {

            Log.e("SPAN",position%3+" <=="+position);
            switch (position % 6) {
                case 0:
                    return 3;
                    break;
                case 1:
                case 2:
                case 3:
                case 4:
                    return 1;
                    break;
                case 5:
                    return 2;
                    break;
                default:return 3;
            }
        }
    });