Home > Software design >  Change icon dynamically in Jetpack Compose
Change icon dynamically in Jetpack Compose

Time:10-12

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?

CodePudding user response:

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