RJnr
RJnr

Reputation: 866

How to change Text value when a button is clicked in Jetpack Compose?

I have three composable buttons and a composable Text() and I want to change the text value of the Text() composable to a particular value when a certain composable button is clicked.

I know how to achieve this in xml by using setText() and I've tried to solve this by using MutableStateOf() but I keep getting it wrong somewhere.

something like this

Upvotes: 8

Views: 11064

Answers (1)

Raw Hasan
Raw Hasan

Reputation: 1396

Try this:

// if you have issue with remember
import androidx.compose.runtime.*
@Composable
fun ChangeText() {
    var text by remember { mutableStateOf("Click a button") }

    Column(modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) {
        Text(text)

        Button(onClick = { text = "Button 1 Clicked" }) {
            Text(text = "Button 1")
        }
        Button(onClick = { text = "Button 2 Clicked" }) {
            Text(text = "Button 2")
        }
        Button(onClick = { text = "Button 3 Clicked" }) {
            Text(text = "Button 3")
        }
    }
}

Upvotes: 15

Related Questions