简体   繁体   中英

Change icon dynamically in Jetpack Compose

I have two icons for "Like" button - ic_thumb_up and ic_thumb_up_selected

The type of icon should depend on the offer.likedByUser parameter.

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 . You are not changing the mutableStateOf in your onClick handler, so nothing happens.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM