androidkotlinandroid-jetpack-composeandroid-tablayoutandroid-scrollable-tabs

Changing Selected Tab Bottom Line Color in Jetpack Compose


I am working on a Jetpack Compose project in Kotlin for Android, and I have implemented a tab layout using ScrollableTabRow. Tabs has a bottom line, and I want to change the color of the selected tab to red. Here's my current code:

var selectedTab by remember { mutableIntStateOf(0) }

Column(modifier = Modifier.fillMaxSize()) {
    ScrollableTabRow(
        modifier = Modifier.fillMaxWidth(),
        selectedTabIndex = selectedTab,
        edgePadding = 0.dp,
        indicator = { _: List<TabPosition> ->
            Modifier.background(Color.Red)
        },
        tabs = {
            tabs.forEachIndexed { index, title ->
                Tab(
                    text = { Text(text = title) },
                    selected = selectedTab == index,
                    onClick = { selectedTab = index },
                )
            }
        }
    )

    TabContent(
        tabTitle = tabs[selectedTab],
        book = books
    )
}

Solution

  • The color of the selected tab indicator can be changed by overriding the indicator parameter of the ScrollableTabRow with the TabRowDefaults.Indicator(), and specifying the indicator offset and the color:

    ScrollableTabRow(
        selectedTabIndex = selectedTab,
        /// ...
        indicator = { tabPositions ->
            if (selectedTab < tabPositions.size) {
                TabRowDefaults.Indicator(
                    modifier = Modifier.tabIndicatorOffset(tabPositions[selectedTab]),
                    color = Color.Red
                )
            }
        }
    ) /// ...