Home > other >  In jetpack compose how to add numbers(counts) near icons(like,comment)
In jetpack compose how to add numbers(counts) near icons(like,comment)

Time:11-17

enter image description here how to add numbers near the icon in android jetapck compose, i have attached snap below like that.please help me to solve the problem.

CodePudding user response:

You can use the BadgedBox.
Use the offset modifier to change the position of the badge, and the containerColor to change the background color.
In M2 the background color is defined by the backgroundColor attribute.

BadgedBox(
    badge = {
        Badge(
            modifier = Modifier.offset(y=10.dp),
            containerColor=LightGray
        ){
            val badgeNumber = "8"
            Text(
                badgeNumber,
                modifier = Modifier.semantics {
                    contentDescription = "$badgeNumber new notifications"
                }
            )
        }
    }) {
    Icon(
        Icons.Filled.Star,
        contentDescription = "Favorite"
    )
}

enter image description here

CodePudding user response:

You can use this code below:

@Composable
fun IconsRow() {
    // Update the texts according to your logic
    var favoriteText by remember { mutableStateOf("34") }
    var repeatText by remember { mutableStateOf("12") }
    var chatText by remember { mutableStateOf("12") }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            IconWithNearbyText(
                text = chatText,
                icon = Icons.Outlined.ChatBubbleOutline
            )
            IconWithNearbyText(
                text = repeatText,
                icon = Icons.Outlined.Repeat
            )
            IconWithNearbyText(
                text = favoriteText,
                icon = Icons.Outlined.FavoriteBorder
            )
        }
    }
}

@Composable
fun IconWithNearbyText(
    text: String,
    icon: ImageVector
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(2.dp)
    ) {
        Icon(imageVector = icon, contentDescription = null)
        Text(text = text)
    }
}
  • Related