Android: How do I get string from resources using its name?

I would like to have 2 languages for the UI and separate string values for them in my resource file resvaluesstrings.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>

Now I need to retrieve these values dynamically in my app:

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);

My problem is that i = 0 .

Why does not it work in my case?


The link you are referring to seems to work with strings generated at runtime. The strings from strings.xml are not created at runtime. You can get them via

String mystring = getResources().getString(R.string.mystring);

getResources() is a method of the Context class. If you are inside a Activity or a Service (which extend Context) you can use it like in this snippet.

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.

See Localization and Providing Resources for more information.


I have the same problem. But this code below works for me: Verify if your packageName is correct. You have to refer for the root package of your Android application.

private String getStringResourceByName(String aString) {
      String packageName = getPackageName();
      int resId = getResources().getIdentifier(aString, "string", packageName);
      return getString(resId);
    }

不仅来自活动:

    public static String byIdName(Context context, String name) {
        Resources res = context.getResources();
        return res.getString(res.getIdentifier(name, "string", context.getPackageName()));
    }
链接地址: http://www.djcxy.com/p/23714.html

上一篇: 在另一个程序集中查找所有嵌入式资源

下一篇: Android:我如何从使用名字的资源获取字符串?