Find view by name

后端 未结 2 1377
感情败类
感情败类 2020-12-03 13:14

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:

相关标签:
2条回答
  • 2020-12-03 13:52

    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.

    0 讨论(0)
  • 2020-12-03 14:15

    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);
    
    0 讨论(0)
提交回复
热议问题