Grid Recyclerview,偶数行中有3列,奇数行中有4列

时间:2017-07-08 08:03:26

标签: android android-recyclerview recycler-adapter android-gridlayout gridlayoutmanager

如何创建一个Grid Recyclerview,其中偶数行为3列,奇数行为4列?

    lLayout = new GridLayoutManager(getActivity(), 4, LinearLayoutManager.VERTICAL, false); // MAX NUMBER OF SPACES

    lLayout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            return (position % 3 == 0 ? 3 : 4);
        }
    });

    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(lLayout);

    if (arrayList != null) {
        adapter = new RecyclerViewAdapter(getActivity(), arrayList);
        recyclerView.setAdapter(adapter);
    }

2 个答案:

答案 0 :(得分:4)

试试这个,

// Create a grid layout with 12 columns
    // (least common multiple of 3 and 4)
 GridLayoutManager manager = new GridLayoutManager(this, 12, GridLayoutManager.VERTICAL, false);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                // 7 is the sum of items in one repeated section
                switch (position % 7) {
                    // first three items span 3 columns each
                    case 0:
                    case 1:
                    case 2:
                        return 4;
                    // next four items span 2 columns each

                    case 3:
                    case 4:
                    case 5:
                    case 6:
                        return 3;
                }
                throw new IllegalStateException("internal error");
            }
        });
        recyclerView.setLayoutManager(manager);

See this:

答案 1 :(得分:0)

尝试这样的事情

 layoutManager = new GridLayoutManager(getActivity(), 4);
    layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (position % 3 == 0)
                return 3; 
            else
                return 4; 
        }
    });
    recyclerView.setLayoutManager(layoutManager);

希望这有帮助