简体   繁体   中英

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?

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);

Try this

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM