我写了这句话:

String Mess = R.string.mess_1 ;

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


当前回答

你可以使用下面的代码:

 getText(R.string.mess_1); 

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

其他回答

我用这个:

String URL = Resources.getSystem().getString(R.string.mess_1);

顺便说一下,也可以在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"

你可以使用下面的代码:

 getText(R.string.mess_1); 

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

你可以直接读取strings.xml中定义的值:

<resources>
    <string name="hello">Hello StackOverflow!</string>
</resources>

并设置为一个变量:

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

但是我们可以在视图中定义字符串:

<TextView
    android:id="@+id/myTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello"/>

解决方案1

Context context;
String mess = context.getString(R.string.mess_1)

解决方案2

String mess = getString(R.string.mess_1)