https://kotlinlang.org logo
m

Mehdi Haghgoo

08/06/2020, 5:21 AM
Another question, how to refer to the current composable in a Modifier? For example, trying to change the text value of a Text modifier using a clickable modifier.
Copy code
Text(text = "Hello Android!", modifier = Modifier.clickable(onClick =  /*Code to change the text Hello Android */))
a

allan.conda

08/06/2020, 5:22 AM
you can’t refer composable since they are functions. use mutable state instead
Copy code
var text by state { "Hello Android" }
Text(text = text, clickable(onClick = { text = "Hi Android" }
j

Joost Klitsie

08/06/2020, 5:35 AM
I think the underlying "issue" is that composables are not the same as Android Views. Old fashioned Android views have their own state, whereas composables do not have their own state. This is why you can do TextView.getText() on an old fashioned android text view and you would never be able to do this with a composable Text, as it simply doesn't know/care. The idea behind this, is that with the new Compose, they wanted to fix the issue where your (View)Model has a state and your View as well, and move to a single source of truth where only your model contains the state and the View doesn't. That is why even a text input cannot update its own value directly when you're typing 🙂 When you type, the onChange method will be fired only. This you should handle yourself by updating the state of the input and setting the current value again from that. Once this happens, compose will notice the changes in the values/states and render it for you.
❤️ 1