How can I dynamically change the background color ...
# compose
k
How can I dynamically change the background color of a row object based on a computed value? For example:
Copy code
val energy = calEnergy(arg1, arg2, arg3, arg4)

var cellColor: Color = if (energy > 50) {
    Color(R.color.warning)
} else if (energy > 20) {
    Color(R.color.acceptable)
} else if (energy > 0) {
    Color(R.color.groovy)
} else {
    Color(R.color.purple_700)
}

Column(modifier - modifier){
    Row(...){
       Box(modifier = modifier.background(color = cellColor)){...}
}
What am I missing here?
z
First of all, generally don’t pass the same modifier instance to multiple composables, unless you’re specifically creating that instance to use multiple places.
😓 1
Otherwise that code looks fine
k
Okay on the modifier. Learning compose still. 😉 The color value isn't changing though for the box element, which is what has me stumped.
z
Can you share more of your code? Maybe there’s something else in the composable that’s affecting things
r
Also you are passing resource IDs as color rgba values
k
@romainguy Doh.... that is indeed a problem. 🤦‍♂️
Mentally stuck in doing things 3-4 years ago.
r
😄
k
Quick code change away from .xml to Color.kt and viola, things work. Thanks @romainguy for that time, and @Zach Klippenstein (he/him) [MOD] for the quick code review to affirm I wasn't (entirely) crazy with my code logic.
r
It’s an easy mistake to make, I notice it quickly because I made myself a few times 😄
🙌 1
I thought we had a lint check for stuff like that 😕
k
Maybe I should turn some of those settings back on. 🤣
r
That or we should beg Jetbrains to give us real types instead of just typealias (although I guess you can do it with value classes kind of)
t
what the heck is
modifier - modifier
going to do... produce a new modifier which does nothing?
r
I'm pretty sure this was supposed to be an =
k
Yes, typo here in Slack.
238 Views