In this article we will see how to make multiple headers for Lazy Column in Jetpack compose.
As you can see in the above video , we have a list of items , and all the items have a type (Animal , Flower, Furniture). We will arrange all the items according to their types and also see show/hide the items.
data class Item( val id: Int, val name: String, val type: String )
First we defined the list of data with their type…
@Composable fun LazyColumnWithMultiHeaderScreen( modifier: Modifier ) {
// a mutable map variable , which indicate that item is visible or not var isShow = remember { mutableStateMapOf<String, Boolean>() }
// by default we will store true , all the item will be visible LaunchedEffect(key1 = Unit) { isShow = isShow.apply { itemList.associate { item -> item.type to true }.also { putAll(it) } } }
As you can see in the above code , First we have defined a isShow variable , which is a mutableStateMapOf<String,Boolean> , which store type (Animals , Flowers , Furniture) and their corresponding true/false value, so that it’s easy to keep track , which item we want to show/hide.
After that in the LaunchEffect we apply all the type to true , because by default all the item will be visible.
Now in the LazyColumn , first we group the items with their type , As you see with the help of groupBy{} kotlin’s in-built function , it will return Map<String, List<Item>> .
After that use forEach loop which will return (type,List<Item>) , In the item{} function , just write your header section with hide/show functionality
And In the items{} function , pass your List<Item> data , and it will show all the items corresponding to their type
That’s all for today my friends , Hope you enjoyed and learnt something new from this article.
Jayant Kumar is a Lead Software Engineer, passionate about building modern Android applications. He shares his expertise in Kotlin, Android, and Compose.