TopAppBar with Tabs renders Tabs with incorrect color

Viewed 409

I'm trying to build component for displaying TopAppBar and Tabs in Jetpack Compose.

Here is the effect I want to achieve: enter image description here

I made wrapper for Tabs:

data class TabElement<T : Enum<T>>(
  val id: T,
  @StringRes val label: Int
)

@Composable
fun <T : Enum<T>> Tabs(
  value: T,
  tabs: List<TabElement<T>>,
  onChange: (T) -> Unit
) {
  TabRow(
    modifier = Modifier
      .height(54.dp)
      .zIndex(2f),
    selectedTabIndex = value.ordinal
  ) {
    for (tab in tabs) {
      Tab(
        selected = value == tab.id,
        text = {
          Text(
            text = stringResource(id = tab.label).toUpperCase(Locale.ROOT),
            fontWeight = FontWeight.Bold
          )
        },
        onClick = {
          onChange(tab.id)
        },
      )
    }
  }
}

And then I used it with default TopAppBar:

@Composable
fun <T : Enum<T>> InternalTopBarWithTabs(
  title: String,
  modifier: Modifier = Modifier,
  actions: @Composable RowScope.() -> Unit = {},
  tabs: List<TabElement<T>>,
  currentTab: T,
  onTabChange: (T) -> Unit
) {
  Column {
    TopAppBar(title = { Text(title) }, modifier = modifier, actions = actions)
    Tabs(value = currentTab, tabs = tabs, onChange = onTabChange)
  }
}

View structure is built correctly, however tabs color is incorrect (I double checked that and TopAppBar color is exactly my primary color set in MaterialTheme, so thge problem is with Tabs). It looks like this: enter image description here enter image description here

I think the problem is somehow related to contentColor property of Tabs, because I can achieve desired colors with contentColor = MaterialTheme.colors.primary, but with this solution also content of tabs (single tab) is colored with primary color.

Can anyone help me?

1 Answers

Remove the .height(54.dp) modifier in the TabRow and apply it to the Tab

TabRow( modifier = Modifier
    //.height(54.dp)
    .zIndex(2f),
    selectedTabIndex = state) {
    titles.forEachIndexed { index, title ->
        Tab(
            modifier = Modifier.height(54.dp),
            /* ...*/
        )
)

With the .height(54.dp) modifier in the TabRow:

enter image description here

Without:

enter image description here

Related