Wafi_ck
Wafi_ck

Reputation: 1378

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?

Upvotes: 8

Views: 6805

Answers (1)

Francesc
Francesc

Reputation: 29260

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

Upvotes: 15

Related Questions