Span size control in recyclerview using layout managers.

Recyclerviews over the time has become the most interesting and perhaps the most complex topics in the android application development space. Not only it provides excellent memory management support but the flexiblilty it provides makes it a hub of endless creativity. Most of us are used to develop recyclerviews with similar view types all over the screen. But recyclerview is made for much more than that. Here is an example of how you can use the layout manager class to create a variable span recyclerview.

Let me sum up in simple terms what is going on here. I am using a grid layout manager instance with 3 span counts to populate my recyclerview. Afterwards I am trying to give different span size to different elements of the recyclerview according to the position. Then I am adding different layouts according to the span sizes of the element. Let us go step by step.

We will start by creating a Grid layout manager instance with span count 3 and orientation as vertical in our Main Activity itself. The grid layout manager instance has a call back method named setSpanSizeLookup which does all the magic here. It gives us getSpanSize method where we can give a span size for each element in the recyclerview (of course less than the maximum span size). The code is given bellow.

In the next step, We will assign different span count to different elements according to its positions. (If this step is not clear refer this article ). First devided all the elements of the recyclerview in group of 6. Then assign different span count for different position using the modulo operatior (by 6) . For example; if postion is 0 or the remainder is 0, assign a span count of 3 which will take the entire screen; if position is 1 or 2 assign 2 spans and so on. Refer the code bellow.

Finally we will end up by adding three different view types to recyclerview elements as per their span size. This is usually done in the adapter class using getItemViewType method. You can populate the view types with what ever data you want. Finally, this view type will give the view a look and feel of having hetrogeneous viewtypes randomly arranged. To make it more appealing just add a background to the recyclerview and also decrease the opacity in the views by your convenience.

If you are looking for the code, visit my github account link bellow.

Any doubts ?? just throw them to me.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store