简体   繁体   English

在 Jetpack Compose 中动态更改图标

[英]Change icon dynamically in Jetpack Compose

I have two icons for "Like" button - ic_thumb_up and ic_thumb_up_selected我有两个“喜欢”按钮的图标 - ic_thumb_upic_thumb_up_selected

The type of icon should depend on the offer.likedByUser parameter.图标的类型应取决于offer.likedByUser参数。

var thumbIcon by remember {
    mutableStateOf(if (offer.likedByUser) R.drawable.ic_thumb_up_selected else R.drawable.ic_thumb_up)
}

IconButton(
    onClick = {
        offer.likedByUser = !offer.likedByUser
    } 
) {
    Image(painter = painterResource(id = thumbIcon) )
}

Why is it not working?为什么它不起作用?

This code这段代码

var thumbIcon by remember {
   mutableStateOf(if (offer.likedByUser) R.drawable.ic_thumb_up_selected else R.drawable.ic_thumb_up)
}

runs only once, and sets the value to either thumbs_up_selected or thumbs_up .只运行一次,并将值设置为thumbs_up_selectedthumbs_up You are not changing the mutableStateOf in your onClick handler, so nothing happens.您没有更改onClick处理程序中的mutableStateOf ,因此什么也没有发生。

You need to change it like this你需要像这样改变它

var thumbIconLiked by remember {
   mutableStateOf(offer.likedByUser)
}

IconButton(
    onClick = {
        thumbIconLiked = !thumbIconLiked
    } 
) {
    Image(
        painter = painterResource(
            id = if (thumbIconLIked) { 
                R.drawable.ic_thumb_up_selected 
            } else { 
                R.drawable.ic_thumb_up 
            }
        )
    )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 动态更改 Jetpack Compose 视图大小 - Change Jetpack Compose view size dynamically 动态更改卡片中的文本 - Jetpack Compose state - dynamically change text in cards - Jetpack Compose state 如何更改 android jetpack compose bottomAppBar 图标色调颜色? - How to change android jetpack compose bottomAppBar icon tint color? Jetpack Compose 图标阴影/高度 - Jetpack Compose icon shadow/elevation 在 Jetpack Compose 中为 Icon 使用 LottieAnimation - Use LottieAnimation in Jetpack Compose for Icon Jetpack Compose 中的图标太模糊 - Icon too blurry in Jetpack Compose 在 Jetpack Compose 中动态显示 AndroidView - Dynamically show AndroidView in Jetpack Compose 在 Jetpack Compose 中更改 android:windowBackground - Change android:windowBackground in Jetpack Compose 如果在 android 喷气背包中为 NavigationBar 组合选择和取消选择图标,如何更改图标,就像我们在 xml 中为选定的 state 使用的选择器一样? - How to change icon if selected and unselected in android jetpack compose for NavigationBar like selector we use in xml for selected state? Jetpack Compose:在 ListItem 中居中图标或尾随元素 - Jetpack Compose: Center Icon or Trailing elements in a ListItem
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM