CodingProfile
CodingProfile

Reputation: 189

Kotlin how to write two conditionals inside one modifier

How to write two conditionals under one Modifier? For example for .background i have one conditional that handles pressed state and other is just for setting background color depending of passed variants. If code is written with two .background modifier then isPressed part is not working.

 Box(
  Modifier
     .pointerInput(Unit) {
       detectTapGestures(
        onPress = {
         try {
             isPressed = true
             awaitRelease()
         } finally {
           isPressed = false
          }
        },
       )
      }
.background(if (!isPressed) Red else DarkRed)
.background(if (variant == VariantButtons.Primary) Red else if (variant == VariantButtons.Green)  Green else Color.Transparent)
)

Upvotes: 0

Views: 141

Answers (1)

gevondov
gevondov

Reputation: 166

If I understand your question correctly you can use only one background modifier and combine statements inside it, just like below:

.background(
    if (isPressed) {
        DarkRed
    } else {
        when (variant) {
            VariantButtons.Primary -> Red
            VariantButtons.Green -> Green
            else -> Color.Transparent
        }
    }
)

Upvotes: 4

Related Questions