1

In Android Jetpack Compose app, I have tried a clickable update on Text.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent { ColorBox() }
    }
}

@Composable
fun ColorBox() {
    val zero = 0
    val full = 255
    var r by remember { mutableStateOf(zero) }
    var g by remember { mutableStateOf(full) }
    var b by remember { mutableStateOf(zero) }
    val color = Color(r,g,b)
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(color)
            .clickable {
                val until = 256
                r = Random.nextInt(until)
                g = Random.nextInt(until)
                b = Random.nextInt(until)
            },
        contentAlignment = Alignment.Center,
    ) {
        Column {
            Text(text = "R:$r, G:$g, B:$b")
            TextField(value = "R:$r, G:$g, B:$b", onValueChange = {})
        }
    }
}

When I click on the screen, the background color changes. I expect both Text and TextField change with respect to the color RGB components. But Text didn't change while TextField changed as expected, as shown in the image below.

after click, the color changed but Text does not update

Doesn't Text Composable run recomposition, and why does not?

Takashi
  • 31
  • 5
  • What do you mean, your code is fine, and the text will be reorganized with RGB changes – Halifax Jan 15 '23 at 03:44
  • I'm sorry, the Random setup is confusing. I'll update the code and add a screenshot. – Takashi Jan 15 '23 at 04:13
  • 2
    I suspect it is a problem with your compose version, because your code is completely correct when I compile and run it here – Halifax Jan 15 '23 at 05:00

1 Answers1

1

The problem was version dependency of UI, thanks @Halifax.

Project: build.gradle:

buildscript {
    ext {
//        compose_ui_version = '1.1.1'
        compose_ui_version = '1.3.3'  // -- (*)
    }
}

Module: build.gradle:

dependencies {
//    implementation 'androidx.compose.material:material:1.1.1'  // -- (*)
    implementation 'androidx.compose.material:material:1.3.1'
}

The version combination marked // -- (*) causes the above problem.

Takashi
  • 31
  • 5