Home > OS >  Is it posible to change layoutmanager for a different viewtype?
Is it posible to change layoutmanager for a different viewtype?

Time:12-01

Actually I have two viewtypes, a recyclerview is showing the elements in a gridLayout fashion.

Problem is that one of those elements in the grid should be show horizontally with a linearlayout aspect and the others as a grid.

How can I manage this ?

override fun getItemViewType(position: Int): Int {
        return if(position %5 == 0) 1 else 0
    }

This is my recyclerview

binding.rv_mylist.adapter = TestAdapter()
binding.rv_mylist.layoutManager = GridLayoutManager(requireContext(), 3)

in conclusion, what I need is that viewtype 1 shows with a LinearLayoutManager and viewtype 0 with a GridLayoutManager

CodePudding user response:

You can achieve this by modify the spanSizeLookup of the GridLayoutManager, i.e.

layoutManager = GridLayoutManager(activity, 2).apply {
    spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
        override fun getSpanSize(position: Int): Int {
            return when(adapter.getItemViewType(position)) {
                 Type.Linear -> 1
                 Type.Grid -> 2
                 else -> 1
            }
        }
    })
}
recyclerView.layoutManager = layoutManager
  • Related