0
int foo = 0xff;

String label = getNameOfFoo(foo);

System.out.println(label);// this should print "foo";

private String getNameOfFoo(int n){
  String ret;

  ///WHAT COULD I DO HERE TO MAKE THIS A REALITY?

  return ret;
}

Before you jump on me with "Why in GOD'S name would you need this?!" I will say that my goal is get around Android's mechanism of identifying my View id's as strings (ie. "id=@+id/user_name") but having to get it back in my code as int user_name = R.id.user_name. This works fine when I know that there is a "user_name" label. But goes to crap when I don't. I'm trying to write a skinnable app that may or may not contain all sorts of things in the xml, and I need a way to inspect the ids as strings.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236
  • It would be nice, if java supported this. Just think about all the swing components, where you always have to set the "name" property... – keuleJ May 25 '11 at 18:00

3 Answers3

2

What you described can't be done in Java. Could you explain your real problem a bit more? I have made a skinnable Android application.

Edit: Does it help you if you can go from name to id instead? You can in that case look at this thread: How do I get the resource id of an image if I know its name?

I did however not solve it that way, and don't see a need for it.

Community
  • 1
  • 1
Kaj
  • 10,862
  • 2
  • 33
  • 27
1

You can use Context.getResources() for this.

int resID = getResources().getIdentifier("label_name", "drawable", "com.test.app");

And the returned resID. If it's 0 then the label is not found. Read here for more about Resources.

ariefbayu
  • 21,849
  • 12
  • 71
  • 92
0

I have an app which is somewhat skinnable; the user can select one of a set of drawable resources to use as a background and I did not wish to hard-code the drawable set. What I did is name the id of each drawable using an identifiable pattern, something like "background_X", where "background_" was fixed and X could be completely free-form.

I then used reflection on the R class to determine at runtime, each of the candidate backgrounds, and presented them to the user by resource ID. When the user made their selection, I stored the reflected name in sharedPrefs rather than the resource ID... this allowed updates (which could potentially re-number each ID) to retain the user's settings.

Reflection can also be used to convert the number (foo) into a name but you need to walk through everything in R.[attr|drawable|id|etc.].* to find the match, and if you add resources to the category you will run the risk of values changing.

mah
  • 39,056
  • 9
  • 76
  • 93