So I am trying to set a string in the string xml resource file but in the middle of the string I need to use a variable defined in my java class, id rather not just split the string into two, is there a way that I can make a variable in the string that I can change in the java class
Asked
Active
Viewed 1,595 times
1
-
I recomend you to pass for this thread [Put variable inside String resource](https://stackoverflow.com/questions/5854647/how-to-put-variable-inside-string-resources) – Alberto Sáez Vela Feb 11 '21 at 09:54
1 Answers
1
You can pass all the parameters that you want to a string resource.
Example:
<string name="string_resource"> My name is %1$s and I am %2$s years old </string>
To pass the parameters use the following function:
getResources().getString(R.string.string_resource, "MyName", "myage");
In kotlin is very similar:
getString(R.string.string_resource, "MyName", "myage")

Alberto Sáez Vela
- 192
- 1
- 7
-
i just tried to put this into my java function in another file but the getResources() turned red, and said "Cannot resolve method 'getResources' in 'questionCreator'" – Sam Parsons Feb 11 '21 at 10:16
-
-
I don't recomend you to pass context as parameter between classes. Pass the string as parameter from activity or fragment – Alberto Sáez Vela Feb 11 '21 at 14:09