cla*_*amp 9 resources android localization
我有一个多语言的Android应用程序,我已将不同的翻译放在strings.xml的相应目录中.
现在我也有一个自定义的xml文件,我想引用这样的文本:
<?xml version="1.0" encoding="UTF-8"?>
<rooms>
<room title="@+string/localizedtext" />
</rooms>
Run Code Online (Sandbox Code Playgroud)
现在当我在我的代码中读取title属性时,我显然得到了未解析的字符串"@ + string/localizedtext".是否有可能以某种方式自动解决此链接到本地化文本?
谢谢!
小智 6
差不多一年后:
public static String getStringResource(Context context, String thingie) {
try {
String[] split = thingie.split("/");
String pack = split[0].replace("@", "");
String name = split[1];
int id = context.getResources().getIdentifier(name, pack, context.getPackageName());
return context.getResources().getString(id);
} catch (Exception e) {
return thingie;
}
}
Run Code Online (Sandbox Code Playgroud)
那就行了.
这似乎是一个广泛的答案,但我相信它会为那些花了几个小时寻找它的人澄清很多东西(我就是其中之一).
简短的回答是肯定的,您可以在自定义XML中使用引用,而不仅仅是字符串,但这是我使用的示例,以便于理解.
考虑到上下文:
<resources>
<string name="sample_string">This is a sample string.</string>
</resources>
Run Code Online (Sandbox Code Playgroud)
<resources>
<string name="sample_string">Ceci est un exemple de chaîne</string>
</resources>
Run Code Online (Sandbox Code Playgroud)
<!-- @string/sample_string identifies both
the default and french localized strings,
the system settings determine which is used at runtime.
-->
<test>
<sample name="sampleName" text="@string/sample_string"/>
</test>
Run Code Online (Sandbox Code Playgroud)
//Omitted imports for clarity.
public class testXmlParser {
public static final String ns = null;
public int parse(XmlResourceParser parser) throws XmlPullParserException,
IOException{
while(parser.next() != XmlPullParser.END_DOCUMENT){
if(parser.getEventType() == XmlPullParser.START_TAG){
if(parser.getName().equalsIgnoreCase("sample")){
// This is what matters, we're getting a
// resource identifier and returning it.
return parser.getAttributeResourceValue(ns, "text", -1);
}
}
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
使用String getText(int id)以取得相应的字符串id(本地化的,如果有的话).
使用上面的例子,它将取代:
//Return the resource id
return parser.getAttributeResourceValue(ns, "text", -1);
Run Code Online (Sandbox Code Playgroud)
用:
//Return the localized string corresponding to the id.
int id = parser.getAttributeResourceValue(ns, "text", -1);
return getString(id);
Run Code Online (Sandbox Code Playgroud)
你尝试的方法是不行的。
您可能会通过<string-array>资源获得类似的功能:
<resources>
<string-array name="room">
<item>@string/localizedText</item>
<item>@string/otherLocalizedText</item>
</string-array>
</resources>
Run Code Online (Sandbox Code Playgroud)
那么你会像这样使用它:
String[] room = getResources().getStringArray(R.array.room);
String localizedText = room[0];
String otherLocalizedText = room[1];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3429 次 |
| 最近记录: |