Android: Set a resource string ID from an ArrayList?
I'm sure there's a better way to do this but I'm rather new to programming altogether so I apologize in advance for my noobiness.
Here's my problem:
I have an ArrayList filled with the name parameters of my strings in strings.xml, what I'm attempting to do is fill a TextView with .setText() utilizing a resource ID that is dynamically created from a part of my array. For example...
ArrayList<String> options = new ArrayList<String>();
options.add("bacon");
options.add("ham");
//R.id.option1 is in my layout and R.string.bacon is in my strings.xml
TextView option1 = (TextView)findViewById(R.id.option1);
option开发者_开发知识库1.setText(R.string.(options.get(0)));
This isn't my complete code obviously. It's just a example faced by the same problem.
Any ideas?
Thanks in advance!
As an idea, instead of a String array of names, you could have an int array of resource ids:
ArrayList<Integer> options = new ArrayList<Integer>();
options.add(R.string.bacon);
options.add(R.string.ham);
//R.id.option1 is in my layout and R.string.bacon is in my strings.xml
TextView option1 = (TextView)findViewById(R.id.option1);
option1.setText(options.get(0));
It sounds like you want to look-up the resource id by name so you can use it in calls that expect the integer id (e.g. in findViewById()):
Resources.getIdentifier()
public int getIdentifier (String name, String defType, String defPackage)
Since: API Level 1
Return a resource identifier for the given resource name. A fully qualified resource name is of the form "package:type/entry". The first two components (package and type) are optional if defType and defPackage, respectively, are specified here. Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
Examples:
String name = "bacon";
int id = resources.getIdentifier(name, "string", "com.package");
if (id == 0) {
Log.e(TAG, "Lookup id for resource '"+name+"' failed";
// graceful error handling code here
}
or
String fullyQualifiedResourceName = "com.package:string/bacon";
int id = resources.getIdentifier(title, null, null);
if (id == 0) {
Log.e(TAG, "Lookup id for resource '"+fullyQualifiedResourceName+"' failed";
// graceful error handling code here
}
精彩评论