Search code examples
androidandroid-recyclerviewandroid-gridlayoutgridlayoutmanager

How to change the spancount for every viewholder with conditions other than position in android


I'm trying to change the spanCount for every viewHolder item in the Recyclerview according to the condition of the data in the items of the recyclerview.Currently, I'm changing the spanCount with the position. But How am I able to change the span of each Items(Viewholder) according to the conditions other than position? For example I want to do like if (type == Item.type) return 1 Some examples or hints would be lovely! I would love to hear from you!

gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
        override fun getSpanSize(position: Int): Int {
            return if (adapter.isMainHead(position) && tabIndex == 0) {
                gridLayoutManager.spanCount
            } else {
                1
            }
        }
    }

Solution

  • Hope this example will help you.

    (layoutManager as GridLayoutManager).setSpanSizeLookup(object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    when (adapter.getItemViewType(position)) {
                        CalendarAdapter.TYPE_HEADER -> return 7
                        CalendarAdapter.TYPE_ITEM -> return 1
                        CalendarAdapter.TYPE_SPAN -> return dataArrayList[position].myVar.toInt()
                        else -> return -1
                    }
                }
            })