徽章

使用 徽章 来显示一个小小的视觉元素,以表示另一个可组合项的状态或数值。以下是您可能使用徽章的一些常见场景:

  • 通知:在应用图标或通知铃上显示未读通知的数量。
  • 消息:在聊天应用中指示新消息或未读消息。
  • 状态更新:显示任务的状态,例如“已完成”、“进行中”或“失败”。
  • 购物车数量:显示用户购物车中的商品数量。
  • 新内容:突出显示用户可用的新内容或功能。
Different example of the badge component.
图 1. 徽章示例

API 界面

使用 BadgedBox 可组合项在您的应用中实现徽章。它本质上是一个容器。您可以通过以下两个主要参数控制其外观:

  • contentBadgedBox 包含的可组合内容。通常是 Icon
  • badge:显示在内容上的徽章可组合项。通常是专用的 Badge 可组合项。

基本示例

此代码段展示了 BadgedBox 的基本实现

@Composable
fun BadgeExample() {
    BadgedBox(
        badge = {
            Badge()
        }
    ) {
        Icon(
            imageVector = Icons.Filled.Mail,
            contentDescription = "Email"
        )
    }
}

此示例显示了一个与所提供的 Icon 可组合项重叠的徽章。请注意代码中的以下几点:

  • BadgedBox 用作整体容器。
  • BadgedBoxbadge 参数的实参是 Badge。由于 Badge 没有自己的实参,因此应用会显示默认徽章,即一个小的红色圆圈。
  • Icon 用作 BadgedBoxcontent 参数的实参。它是徽章显示在其上的图标。在此示例中,它是一个邮件图标。

显示效果如下:

A simple badge that contains no content.
图 2. 最小徽章实现。

详细示例

以下代码段演示了如何在徽章中显示响应用户操作的值。

@Composable
fun BadgeInteractiveExample() {
    var itemCount by remember { mutableStateOf(0) }

    Column(
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        BadgedBox(
            badge = {
                if (itemCount > 0) {
                    Badge(
                        containerColor = Color.Red,
                        contentColor = Color.White
                    ) {
                        Text("$itemCount")
                    }
                }
            }
        ) {
            Icon(
                imageVector = Icons.Filled.ShoppingCart,
                contentDescription = "Shopping cart",
            )
        }
        Button(onClick = { itemCount++ }) {
            Text("Add item")
        }
    }
}

此示例实现了一个购物车图标,徽章显示用户购物车中的商品数量。

  • BadgedBox 仅在商品数量大于 0 时才显示。
  • containerColorcontentColor 的实参控制徽章的外观。
  • Badge 的 content 插槽的 Text 可组合项显示在徽章内。在此示例中,它显示购物车中的商品数量。

此实现效果如下:

A badge implementation that contains the number of items in a shopping cart.
图 3. 显示购物车中商品数量的徽章。

其他资源