2 years ago

#54873

test-img

yoni

Persistant dynamick color

I'm trying to create a clickable card that changed its color after it is clicked. I have (code relevant to the question is documented as "This is relevant to the question") :

    val selectedCardColor by remember {
        mutableStateOf(Color(0xFF00FFFF))
    }
    val unselectedCardColor by remember {
        mutableStateOf(Color(0xAA007777))
    }

               // This is relevant to the question
    var hmsToDecColor by remember {
        mutableStateOf(selectedCardColor)
    }

               // This is relevant to the question
    var decToHmsColor by remember {
        mutableStateOf(unselectedCardColor)
    }

...

   Card(
       modifier = Modifier
           .weight(0.5f)
           .padding(1.dp)
           .clickable {
                         // This is relevant to the question
               hmsToDecColor = unselectedCardColor
               decToHmsColor = selectedCardColor
               onClick(true)
           },
           border = BorderStroke(1.dp, Color.Black),
           elevation = 4.dp
       ) {
              Text(
                  text = str1,
                  textAlign = TextAlign.Center,
                  color = MaterialTheme.colors.onSecondary,
                  modifier = Modifier
                      .background(hmsToDecColor)      // This is relevant to the question
                      .padding(20.dp)
              )
         }

(There is another one that toggles the other way). Everything works as planned. When I hit the card the color changes but... When I rotate the phone the colors are back to the default as if nothing was done. I can not figure out why the "remember" does not remember...

I understand that everything is recomposed but expected the "remember" to persist.

I assume that the variables do remember but the fresh recomposition ignores the remembered value and uses the coded ones. If this is the case, how do I overcome this?

android

kotlin

android-jetpack-compose

android-jetpack

0 Answers

Your Answer

Accepted video resources