我写了这句话:

String Mess = R.string.mess_1 ;

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


当前回答

你可以直接读取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)

你可以使用下面的代码:

 getText(R.string.mess_1); 

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

**

我希望这个代码是有益的

**

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

在活动:

this.getString(R.string.resource_name)

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

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

更新

你可以在Activity或Fragment中使用getString(r.r estring .some_string_id)。 你可以使用Context.getString(r.r string.some_string_id),你不能直接访问getString()方法。像对话框。

问题是你没有Context访问,就像Util类中的一个方法。

假设下面的方法没有上下文。

public void someMethod(){
    ...
    // can't use getResource() or getString() without Context.
}

现在您将在该方法中传递Context作为参数,并使用getString()。

public void someMethod(Context context){
    ...
    context.getString(R.string.some_id);
}

我所做的是

public void someMethod(){
    ...
    App.getRes().getString(R.string.some_id)
}

什么?这是非常简单的使用任何地方在您的应用程序!

所以这里有一个奖金独特的解决方案,通过它你可以从任何地方访问资源,比如Util类。

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static App mInstance;
    private static Resources res;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        res = getResources();
    }

    public static App getInstance() {
        return mInstance;
    }

    public static Resources getResourses() {
        return res;
    }

}

在manifest.xml <application标签中添加name字段。

<application
        android:name=".App"
        ...
        >
        ...
    </application>

现在可以开始了。