如何在我的代码中提取String资源?

时间:2016-05-28 13:31:16

标签: android

当我像这样添加字符串作为参数时,一切正常:

mPages[0] = new Page(
                R.drawable.page0,
                "On your return trip from studying Saturn's rings, you hear a distress signal that seems to be coming" +
                        " from the surface of Mars. It's strange because there hasn't been a colony there in years. " +
                        "Even stranger, it's calling you by name: \"Help me, %1$s, you're my only hope.\"",
                new Choice("Stop and investigate", 1),
                new Choice("Continue home to earth", 2));

但是,当我尝试像这样提取字符串资源时,会出现错误

mPages[0] = new Page(
                R.drawable.page0,
                .getString(R.string.story_page0),
                new Choice("Stop and investigate", 1),
                new Choice("Continue home to earth", 2));

那我该怎么办?

3 个答案:

答案 0 :(得分:0)

;后删除.getString(R.string.story_page0)并添加,。应该是

mPages[0] = new Page(
            R.drawable.page0,
            getApplicationContext().getResources().getString(R.string.story_page0),   //--here
            new Choice("Stop and investigate", 1),
            new Choice("Continue home to earth", 2));

答案 1 :(得分:0)

您无法直接致电getString

您需要先获取Resources个对象,然后在该对象上调用getString

要获取Resources对象,您需要Context。如果您的代码位于ActivityContext的子类中,则可以使用this。现在,我假设你是。

让我们首先通过调用来获取资源:

Resources res = getResources();

然后我们调用getString来获取字符串:

String s = res.getString();

然后你只需创建Page或其他:

mPages[0] = new Page(
                R.drawable.page0,
                s,
                new Choice("Stop and investigate", 1),
                new Choice("Continue home to earth", 2));

答案 2 :(得分:0)

尝试使用:

mPages[0] = new Page(
            R.drawable.page0,
            string.valueOf(R.string.story_page0),
            new Choice("Stop and investigate", 1),
            new Choice("Continue home to earth", 2));

并且建议使你的所有字符串像#34;停止并调查"和#34;继续回到地球"在您的String.xml文件中