我想有2种语言的UI和单独的字符串值为他们在我的资源文件res\values\strings.xml:
<string name="tab_Books_en">Books</string>
<string name="tab_Quotes_en">Quotes</string>
<string name="tab_Questions_en">Questions</string>
<string name="tab_Notes_en">Notes</string>
<string name="tab_Bookmarks_en">Bookmarks</string>
<string name="tab_Books_ru">Книги</string>
<string name="tab_Quotes_ru">Цитаты</string>
<string name="tab_Questions_ru">Вопросы</string>
<string name="tab_Notes_ru">Заметки</string>
<string name="tab_Bookmarks_ru">Закладки</string>
现在我需要在我的应用程序中动态检索这些值:
spec.setContent(R.id.tabPage1);
String pack = getPackageName();
String id = "tab_Books_" + Central.lang;
int i = Central.Res.getIdentifier(id, "string", pack);
String str = Central.Res.getString(i);
我的问题是i = 0。
为什么它对我没用?
您所引用的链接似乎与运行时生成的字符串一起工作。strings.xml中的字符串不是在运行时创建的。
你可以通过
String mystring = getResources().getString(R.string.mystring);
getResources()是Context类的一个方法。如果您在一个活动或服务(扩展上下文)中,您可以像下面这样使用它。
Also note that the whole language dependency can be taken care of by the android framework.
Simply create different folders for each language. If english is your default language, just put the english strings into res/values/strings.xml. Then create a new folder values-ru and put the russian strings with identical names into res/values-ru/strings.xml. From this point on android selects the correct one depending on the device locale for you, either when you call getString() or when referencing strings in XML via @string/mystring.
The ones from res/values/strings.xml are the fallback ones, if you don't have a folder covering the users locale, this one will be used as default values.
有关更多信息,请参见本地化和提供资源。
如果你在使用Kotlin,你可以这样定义一个扩展函数:
fun Context.getStringResourceByName(stringName: String): String? {
val resId = resources.getIdentifier(stringName, "string", packageName)
return getString(resId)
}
然后简单地使用它。例如,在一个拼图应用程序中,我根据图像文件名设置活动标题:
val stringName = "${folderName}_${assetName.substringBefore(".")}"
title = getStringResourceByName(stringName)
在这个例子中,我正在读取基于动态名称的字符串资源。