Android 根据运行时值获取资源字符串
Android Getting resource string based on runtime value
有没有办法根据运行时值从我的 "strings.xml" 获取特定资源?
为了解释更多,我有一个值列表,即每个地点的出租车费 - 即班加罗尔、金奈等不同。
我的 Strings.xml 看起来像这样:
<string-array name="Bengaluru">
<item>Min Fare | 100</item>
<item>Per KM Fare |10</item>
</string-array>
在我的 MainActivity 中,我使用如下代码:
String currentCity = <Getting the city via phone location method>
if(currentCity.equals("Bengaluru")) {
// My method to extract values from the string
myCustomParser(getResources().getStringArray(R.array.Bengaluru));
}
(我可能会将 if 替换为 Switch-Case,但是没有办法将上面的代码重写为:
// My method to extract values from the string
myCustomParser(getResources().getStringArray(R.array.currentCity));
即动态替换我要从资源文件中拉出的值?
谢谢
是的,您可以使用 Resources.getIdentifier(String name, String defType, String defPackage)
。
使用示例:
myCustomParser(getResources().getStringArray(
getResources().getIdentifier("Bengaluru", "array", getPackageName()));
有没有办法根据运行时值从我的 "strings.xml" 获取特定资源?
为了解释更多,我有一个值列表,即每个地点的出租车费 - 即班加罗尔、金奈等不同。
我的 Strings.xml 看起来像这样:
<string-array name="Bengaluru">
<item>Min Fare | 100</item>
<item>Per KM Fare |10</item>
</string-array>
在我的 MainActivity 中,我使用如下代码:
String currentCity = <Getting the city via phone location method>
if(currentCity.equals("Bengaluru")) {
// My method to extract values from the string
myCustomParser(getResources().getStringArray(R.array.Bengaluru));
}
(我可能会将 if 替换为 Switch-Case,但是没有办法将上面的代码重写为:
// My method to extract values from the string
myCustomParser(getResources().getStringArray(R.array.currentCity));
即动态替换我要从资源文件中拉出的值?
谢谢
是的,您可以使用 Resources.getIdentifier(String name, String defType, String defPackage)
。
使用示例:
myCustomParser(getResources().getStringArray(
getResources().getIdentifier("Bengaluru", "array", getPackageName()));