Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
Wafi_ck Avatar asked Jun 13 '26 02:06

Wafi_ck


1 Answers

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 
            },
            contenDescription = "thumb",
        )
    )
}
like image 65
Francesc Avatar answered Jun 18 '26 00:06

Francesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!