Reputation: 376
Like the title said I need to get text from string.xml and the problem is that it gets this error:
@Composable invocations can only happen from the context of a @Composable function
@Composable
fun buttonClick() {
var text = ""
//needs this modifier for component click
var modifier: Modifier = Modifier.clickable() {
text = stringResource(id = R.string.app_name) //this is where warning is
}
}
This is what I need inside of the function, how can I get it?
.clickable {
stringResource(id = R.string.app_name)
}
Upvotes: 2
Views: 746
Reputation: 12953
clickable
invokes a regular function rather than @Composable
function as per the docs.
stringResource
is a composable function which could not be invoked from non compose scope. In order to achieve this, you could either use
@Composable
fun buttonClick() {
var text = ""
val appName by remember { stringResource(id = R.string.app_name) }
var modifier: Modifier = Modifier.clickable() {
text = appName
}
}
var textId: Int = -1
var modifier: Modifier = Modifier.clickable() {
textId = R.string.app_name
}
//while invoking
stringResource(textId)
}
Upvotes: 1
Reputation: 1512
Try this,
val context = LocalContext.current
var text = ""
Button(
onClick = {
text = context.getString(R.string.app_name)
}
) {
Text(text = "Hit me")
}
You can use LocalContext to access getString.
Upvotes: 2