带有标签的 TopAppBar 呈现颜色不正确的标签

时间:2021-05-10 20:02:37

标签: android android-jetpack-compose

我正在尝试构建用于在 Jetpack Compose 中显示 TopAppBar 和 Tabs 的组件。

这里是我想要达到的效果: enter image description here

我为标签做了包装:

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)
        },
      )
    }
  }
}

然后我将它与默认的 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)
  }
}

视图结构正确构建,但是选项卡颜色不正确(我仔细检查了一下,TopAppBar 颜色正是我在 MaterialTheme 中设置的主要颜色,所以问题出在选项卡上)。它看起来像这样: enter image description here enter image description here

我认为问题在某种程度上与 Tabs 的 contentColor 属性有关,因为我可以使用 contentColor = MaterialTheme.colors.primary 获得所需的颜色,但使用此解决方案,标签的内容(单个标签)也使用原色着色。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:3)

移除 .height(54.dp) 中的 TabRow 修饰符并将其应用于 Tab

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

.height(54.dp) 中使用 TabRow 修饰符:

enter image description here

没有:

enter image description here