RecyclerView LayoutManager different span counts on different rows

前端 未结 2 1815
时光取名叫无心
时光取名叫无心 2020-12-08 02:27

I want a RecyclerView.LayoutManager that allows me to specify different span counts for different rows as a repeating pattern. For example 2,3 with 10 items wou

相关标签:
2条回答
  • 2020-12-08 03:09

    To do what you want, you probably have to write your own LayoutManager.

    I think this is easier:

        // Create a grid layout with 6 columns
        // (least common multiple of 2 and 3)
        GridLayoutManager layoutManager = new GridLayoutManager(this, 6);
    
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                // 5 is the sum of items in one repeated section
                switch (position % 5) {
                // first two items span 3 columns each
                case 0:
                case 1:
                    return 3;
                // next 3 items span 2 columns each
                case 2:
                case 3:
                case 4:
                    return 2;
                }
                throw new IllegalStateException("internal error");
            }
        });
    

    If your grid item needs to know its span size, you can find it like this within ViewHolder:

            // this line can return null when the view hasn't been added to the RecyclerView yet
            RecyclerView recyclerView = (RecyclerView) itemView.getParent();
            GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
            int spanSize = gridLayoutManager.getSpanSizeLookup().getSpanSize(getLayoutPosition());
    
    0 讨论(0)
  • 2020-12-08 03:17

    here's how to do it in kotlin:

    val layoutManager= GridLayoutManager(activity, 3)
    layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
        override fun getSpanSize(position: Int): Int {
            return when (position) {
                0 -> 3
                else -> 1
            }
        }
    }
    recyclerView.layoutManager = layoutManager
    

    here, first we have created a grid layout manager with 3 columns, then we have specified the first will occupy the whole 3 columns while the rest take only one.

    0 讨论(0)
提交回复
热议问题