我写了这句话:

String Mess = R.string.mess_1 ;

获取字符串值,但不是返回字符串,而是返回integer类型的id。如何获取它的字符串值?我提到了string.xml文件中的字符串值。


当前回答

在活动:

this.getString(R.string.resource_name)

如果不在活动中,但可以访问上下文:

context.getString(R.string.resource_name)
application.getString(R.string.resource_name)

其他回答

如果你在一个活动中,你可以使用

getResources().getString(R.string.whatever_string_youWant);

如果您不在活动中 用这个:

getApplicationContext.getResource().getString(R.String.Whatever_String_you_want)

顺便说一下,也可以在strings.xml中创建字符串数组,如下所示:

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

然后从你的Activity中你可以得到这样的引用:

String[] tab_names = getResources().getStringArray(R.array.tab_names);
String tabname1=tab_names[0];//"My Tab 1"

**

我希望这个代码是有益的

**

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

你可以使用下面的代码:

 getText(R.string.mess_1); 

基本上,您需要将资源id作为参数传递给getText()方法。

在Android中使用getResources()之前必须引用Context名称。

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

OR

Context mcontext=getApplicationContext();

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