Home > Software engineering >  How do I use the $name parameter in Kotlin using composable
How do I use the $name parameter in Kotlin using composable

Time:01-31

I want to use a string resource with composable functions, I adjusted my code, but it tells me that I have an unused parameter - name("Zero")

 string name="greeting">Hello, my name is $name</string>

 //this one works fine but I don't want to use this one --
 string name="greeting1">Hello, my name is %1$s</string>


@Composable
fun Greeting(name: String) {
Surface(color = Color.Green, border = BorderStroke(1.dp, color = Color.Cyan)) {
    //Text(text = "Hello, my name is $name!", modifier = Modifier.padding(24.dp))
    Text(text = stringResource(id = R.string.greeting1,"Zero"))
}

}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
GreetingCardTheme {
    Greeting("Zero")
}

}

CodePudding user response:

You have

Parameter 'name' is never used

because you have a parameter declared in your composable "name" and you are not using it since you have a fixed string "Zero".

fun Greeting(name: String) {
    //...You are not using name   
    Text(text = stringResource(id = R.string.greeting1,"Zero"))
}

Instead use:

Text(text = stringResource(id = R.string.greeting1,name))

In any case in strings.xml you can also use:

<string name="greeting">Hello, my name is</string>

and in your composable:

Text(text = stringResource(id = R.string.greeting)  " $name")
  • Related