【问题标题】:Can not get strings from string.xml [duplicate]无法从 string.xml 获取字符串 [重复]
【发布时间】:2015-08-28 23:16:27
【问题描述】:

用这个答案解决了How can I get a resource content from a static context?

今天我决定我的应用程序应该支持不同的语言,所以我更改了每个普通字符串,例如...:

String hw = "hello world";

..to:

XML:

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

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

但由于某种原因,它不再显示文本。当我使用正常的方法时,一切都很好,但现在却不行。我也试过 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);

【问题讨论】:

  • “我也尝试过 getText()” 尝试过如何使用?您是否使用日志或断点来查看 hw 是什么?
  • String hw = (String) getText(R.string.hello_world);

标签: java android xml string


【解决方案1】:

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

【讨论】:

  • 试过了还是不行
  • 这就是 OP 已经在做的事情。只是在添加到列表之前尝试将其添加到 String 变量中
  • @Silas 我编辑了我的代码重新检查它。
  • 不幸的是仍然无法正常工作
  • @Silas 代码有什么问题?数据为空还是有异常?
【解决方案2】:

好吧,关键是您需要主要活动的上下文。

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

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

如果是这种情况,你可以这样做:

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

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

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

 Context context = this;

第 2 步:将上下文传递给所需的任何类,然后像在主要活动中使用“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);

这应该可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-07
    • 2020-03-29
    • 2020-03-09
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多