无法从string.xml获取字符串

时间:2015-06-12 20:25:43

标签: java android xml string

通过此回答How can I get a resource content from a static context?

解决

今天我决定我的应用程序应该以不同的语言提供,所以我改变了所有正常的字符串,如...:

String hw = "hello world";

..为:

XML:

<string name="hello_world">Hello world!</string>
App:

String hw= getResources().getString(R.string.hello_world);

但由于某种原因,它不再显示文字了。当我使用正常方法时,Everthing工作正常,但现在却没有。我也尝试了getText(),但这也不起作用。我正在使用字符串将它们放入这样的ArrayList中:

public  hello(){

    meineListe.add(hello_world);

完整课程:

public class favorites extends Activity {

static int x = -1;

private ArrayList<String> meineListe = new ArrayList<String>();

public  favorites(){
    String a1 = getResources().getString(R.string.a1);
    String aa1 = getResources().getString(R.string.aa1);
    String aaa1 = getResources().getString(R.string.aaa1);

2 个答案:

答案 0 :(得分:1)

尝试 - meineListe.add(getResources().getString(R.string.hello_world)); 并确保在res / values / strings.xml文件中声明了字符串。

答案 1 :(得分:0)

好的,重点是你需要主要活动的背景。

我不确定你在哪里调用getResources()。getString bla bla,但是,它是这样的:

案例1:您在主要活动中调用它。

如果是这种情况,请执行以下操作:

 String hw= this.getResources().getString(R.string.hello_world);

CASE2:你在其他一些类/活动/片段中调用它吗?

步骤1:在您的主要活动中添加以下代码:

 Context context = this;

第二步:你将上下文传递给你想要的任何类,你就像在主活动中使用“this”一样使用它。

 Context context;
 //
 //Code,variables,whatever you got there
 //

 //In your constructor, or method which you used to pass the context from main activity:

 context.this = context;
 String hw= context.getResources().getString(R.string.hello_world);

这应该可以解决问题。