androidkotlinandroid-jetpack-composeandroid-tabsandroid-jetpack-compose-material3

How can I create scrollable tabs using Jetpack Compose?


I want to create the kind of "tabs" that Whatsapp has (all, unread, groups) whatsapp tab image but they also have to be scrollable. But, I am not sure what the tabs are even called since the width for each "tab" is sized according to the width of the title. How can I achieve this using Jetpack Compose?

Thank you and I really appreciate the help!


Solution

  • A FilterChip might be what you are looking for. You can put them into a Row and apply the horizontalScroll Modifier to make the Row scrollable if the FilterChips exceed the screen width.

    Please try the following code:

    @Composable
    fun FilterChipExample() {
    
        val filterLabels = remember {
            listOf("All", "Unread", "Groups")
        }
    
        var selectedIndex by remember {
            mutableIntStateOf(-1)
        }
    
        Column {
    
            Row(
                modifier = Modifier.horizontalScroll(rememberScrollState())
            ) {
                filterLabels.forEachIndexed() { thisIndex, filterLabel ->
                    FilterChip(
                        modifier = Modifier.padding(8.dp),
                        onClick = {
                            selectedIndex = if (selectedIndex == thisIndex) {
                                -1
                            } else {
                                thisIndex
                            }
                                  },
                        label = {
                            Text(filterLabel)
                        },
                        selected = selectedIndex == thisIndex
                    )
                }
            }
    
            when(selectedIndex) {
                0 -> {
                    Text(modifier = Modifier.padding(16.dp), text = "Showing all Chats...")
                }
                1 -> {
                    Text(text = "Showing unread Chats...")
                }
                2 -> {
                    Text(modifier = Modifier.padding(16.dp), text = "Showing Groups...")
                }
                else -> {
                    Text(modifier = Modifier.padding(16.dp), text = "Nothing selected")
                }
            }
        }
    }
    

    Output: