Reputation: 73
I use Jetpack compose for an android app.I want to retrieve the String value of a String that is already declared in Resources.Strings. I tried everything even context but nothings seems to work.
More specifically I want to register a String value from Resources as the contentDescription of composable's modifier so that TalkBack can read this value to the user's system language.The debugger logs an int value instead of a String even when I user .toString()
method. Here is the code.
This is the string on values/strings.xml
file.
<string name="my_string">Something</string>
This is some of the code for the composable:
....modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequesters[1])
.clearAndSetSemantics { contentDescription = R.string.mystring.toString() }
)
val test= (R.string.my_string)
Log.d("Test",""+ test )
The debugger shows an integer value to the Android Studio's Logcat. This is output of the Logcat:
D/Test: 2131623845
The expected result should have been:
D/Test: Something
Upvotes: 2
Views: 6203
Reputation: 1950
As far as I'm aware, there are currently two ways to do this:
String
prepared beforehand, as it is done in Gabriele Mariotti's example, by using the @Composable
stringResource
function;Context
variable prepared beforehand and then use context.getString()
:@Composable
fun SomeFunction() {
val context = LocalContext.current
TextField(
label = { Text(stringResource(R.string.some_label)) },
modifier = Modifier.semantics {
contentDescription = context.getString(R.string.some_description)
}
)
}
Upvotes: 6
Reputation: 364506
Just use the method stringResource
:
val test = stringResource(R.string.my_string)
Text("text",
modifier = Modifier
.fillMaxWidth()
.clearAndSetSemantics {contentDescription = test}
)
Upvotes: 5