Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

java - Access a resource name programmatically

I have many string arrays in my resource files, and I want to access them programmatically depending on user input.

int c = Getter.getCurrentNumber();
String[] info = getResources().getStringArray(R.array.n_<c>);

So if c==12, info should be the string-array with name "n_12". Is there a way to do this, and avoiding to do a switch statement with hundreds of cases?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can get the resource id like so

int c = Getter.getCurrentNumber();
String resource = "n_" + c;
int id = getResources().getIdentifier(resource, "array", "com.your.project");

Then just use that id

String[] info = getResources().getStringArray(id);

Have a look here for another example on getResources().getIdentifier().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...