levente
levente

Reputation: 95

How do I set text of TextView to a string resource? (Java for android)

I would like to change the text of a TextView component to another text, that I have already created in strings.xml. When the app starts, the text shown is stored in strings.xml, under the name "help0". I would like to set this to the string under the name "help00" programmatically, by placing another "0" at the and of the name. So far I have written this code :

String help = "0";
help = help + "0";
final TextView help = (TextView) findViewById(R.id.help);
help.setText("@string/help" + help);

However, when I run the app the text changes to "@string/help00", instead of the text I have stored under help00 in strings.xml.

How could I fix this problem?

Upvotes: 3

Views: 32542

Answers (3)

Waddah Mustafa
Waddah Mustafa

Reputation: 31

I believe that strings.xml resource file content cannot be edited during runtime. now i am assuming u have the following on your strings.xml file

<resources>
    <string name="app_name">Application Name</string>
    <string name="help0">Text1</string>
    <string name="hellp00">Text2</string>
</resources>

if u want to change the text on your TextView (id=@+id/textview) from the value stored as "help0",to value stored in "help00" use the following code:

String text= getString(R.string.help00);
TextView myTextView = findViewById(R.id.textview);
myTextView.setText(text);

Upvotes: 3

user370305
user370305

Reputation: 109237

Because You have concatted String resource id with normal String help So its worked as a String. You have to get first resource string from android resource and then need to concat with local String variable, like,

help.setText(getResources().getString(R.string.help)+help);

As I doubt, if you are looking for dynamically String id, You want String resource id with already exist id and '0' append to it then get int resource id from String using..

int resourceId = this.getResources().getIdentifier("@string/help" + help, "string", this.getPackageName());

and then

help.setText(resourceId);

Upvotes: 11

Marcus
Marcus

Reputation: 6717

Try this

String help = "0";
final TextView tvHelp = (TextView) findViewById(R.id.help);
String yourString = getResources().getString(R.string.help);
tvHelp.setText(yourString +help)

Upvotes: 4

Related Questions