In Android, to access a string from the strings.xml file, we use R.string.string_id. Would it be possible to have a method such that we'll use the string form of string_id? I mean can we for example have a method GetString("string_id") to retrieve R.string.string_id?
2 Answers
//Replace this with appropriate context
String name = "name_of_your_string_in_strings_xml_file_goes_here";
int resId = this.getResources().getIdentifier(name, "string", this.getPackageName());
String string = this.getResources().getString(resId);
1 Comment
It is possible. You have to understand the fact that any data that is pinned to xml files in android are considered as resource to the app. And android resource can be accessed only by means of unique id we provide to them. These ids that are generated are of type int and hence we need to pass a int parameter to get a reference to these resource at run time.
But it is not that only the default way to access them is by using their res value but instead if you could know the name of the string key you could find the id from there and then use the int id to do this.