使用GridLayoutManager为每一行设置不同的范围

时间:2018-04-19 11:24:08

标签: android android-recyclerview 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被视为项目)

  • 单个ImageView的第一行

  • 第二行有三个ImageView

  • 带有两个ImageView的第三行。

2 个答案:

答案 0 :(得分:1)

您的逻辑似乎存在问题。尝试使用以下逻辑:

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

答案 1 :(得分:0)

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)