请参阅我之前的问题here了解完整代码。
如果我想要将我的应用程序国际化,我需要为项目中的某些语句创建字符串对象。困扰我最多的是这个代码块。
...
else
Toast.makeText(MainActivity.this,
"Good job! The answer was " + comp + ".\n" +
"You made " + guesses + " guesses.\n" +
"Restart the app to try again.",
Toast.LENGTH_LONG).show();
}
};
strings.xml中与此相关的部分如下所示:
<string name="correct">Good job! The answer was + comp\n
You made + guesses + guesses.\n
Restart the app to try again.</string>
我希望comp和猜测变量显示各自的值,但我不知道如何。
我计划对代码块执行此操作
...
else
Toast.makeText(MainActivity.this,
R.string.correct,
Toast.LENGTH_LONG).show();
}
};
谢谢。
答案 0 :(得分:13)
在xml文件string.xml中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="correct">Good job! The answer was %1$s\n
You made %2$s guesses.\n
Restart the app to try again.</string>
</resources>
如果您想在文本中添加其他值,则增加%2 $ s - &gt; %3 $ s等...
然后你可以像在java中一样使用它:
Toast.makeText(MainActivity.this, getString(R.string.correct, comp, guesses),
Toast.LENGTH_LONG).show();
答案 1 :(得分:1)
在资源中存储格式字符串,并使用String.format替换 comp 和猜测占位符。为每个使用适当的占位符,并将变量包含为format()的参数。您可以在Formatter class下找到要使用的占位符的详细信息。
该资源将类似于:
<string name="correct">Good job! The answer was %s \n
You made %d guesses.\n
Restart the app to try again.</string>
代码将是:
...
else
String correctFormat = getString(R.string.correct);
Toast.makeText(MainActivity.this,
String.format(correctFormat, comp, guesses),
Toast.LENGTH_LONG).show();
}
};
答案 2 :(得分:0)
你会用
context.getResources().getString(r.id.correct);
然后为您想要的每种语言创建一个值文件夹
答案 3 :(得分:0)
正如@Andros所说,
在你的string.xml中
<string name="correct">Good job! The answer was %1$s\n
You made %2$s guesses.\n
Restart the app to try again.</string>
在您的代码中,
Resources res = getResources();
Toast.makeText(MainActivity.this, String.format(res.getString(R.string.correct),comp, guesses),Toast.LENGTH_LONG).show();
答案 4 :(得分:0)
在string.xml中
<string name="correct" formatted="false">Good job! The answer was %s\n
You made %s guesses.\n
Restart the app to try again.</string>
在java中:
Toast.makeText(MainActivity.this,String.format(context.getString(R.string.correct),comp,guesses), Toast.LENGTH_LONG).show();