how to read value from string.xml in android?

2019-01-03 03:55发布

I have written the line:

String Mess = R.string.mess_1 ;

to get string value, but instead of returning string, it is giving me id of type integer. How can I get its string value? I mentioned the string value in the string.xml file.

16条回答
我只想做你的唯一
2楼-- · 2019-01-03 04:35

In Activity:

this.getString(R.string.resource_name)

If not in activity but have access to context:

context.getString(R.string.resource_name)
application.getString(R.string.resource_name)
查看更多
Rolldiameter
3楼-- · 2019-01-03 04:36

By the way, it is also possible to create string arrays in the strings.xml like so:

<string-array name="tabs_names"> 
    <item>My Tab 1</item> 
    <item>My Tab 2</item>
</string-array>

And then from your Activity you can get the reference like so:

String[] tab_names = getResources().getStringArray(R.array.tab_names);
String tabname1=tab_names[0];//"My Tab 1"
查看更多
时光不老,我们不散
4楼-- · 2019-01-03 04:38

**

I hope this code is beneficial

**

String user = getResources().getString(R.string.muser); 
查看更多
相关推荐>>
5楼-- · 2019-01-03 04:39

Try this

String mess = getResources().getString(R.string.mess_1);

UPDATE

String string = getString(R.string.hello);

You can use either getString(int) or getText(int) to retrieve a string. getText(int) will retain any rich text styling applied to the string.

Reference: https://developer.android.com/guide/topics/resources/string-resource.html

查看更多
混吃等死
6楼-- · 2019-01-03 04:45

Only for future references.

In the String resources documentation it says:

You can use either getString(int) or getText(int) to retrieve a string. getText(int) will >retain any rich text styling applied to the string.

查看更多
来,给爷笑一个
7楼-- · 2019-01-03 04:46

You must reference Context name before using getResources() in Android.

String user=getApplicationContext().getResources().getString(R.string.muser);

OR

Context mcontext=getApplicationContext();

String user=mcontext.getResources().getString(R.string.muser);
查看更多
登录 后发表回答