28

Is it possible to find a view by its name rather than its id.

findViewById(R.id.someView);

but I would like to do something like this:

findViewByName("someView");
Drejc
  • 14,196
  • 16
  • 71
  • 106
  • Possible duplicate of [How do I get the resource id of an image if I know its name?](http://stackoverflow.com/questions/3042961/how-do-i-get-the-resource-id-of-an-image-if-i-know-its-name) – ACBM Nov 16 '15 at 00:53

2 Answers2

69

you have to find views by identifier when dealing with xml, but you can look up the identifier by using getIdentifier(String name, ...) which is useful if you have your layouts numbered for example. Just be aware that such a lookup is relatively expensive.

to complete the answer

int id = getResources().getIdentifier(name, "id", context.getPackageName());
View view = findViewById(id);
Drejc
  • 14,196
  • 16
  • 71
  • 106
MrJre
  • 7,082
  • 7
  • 53
  • 66
4

Yes, we can find any static resources by name too.

 int id = getResources().getIdentifier(name, "id", context.getPackageName());
View view;
if(id != 0) {
  view = findViewById(id);
}

getResources().identifier will return 0 always if resource not found or name doesn't match.

Pankaj kumar
  • 1,357
  • 14
  • 13
  • 4
    And how is this different from @MrJre answer? ... don't clutter the site with duplicates. – Drejc Jun 26 '15 at 07:54