按名称查找视图 [英] Find view by name

查看:35
本文介绍了按名称查找视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过名称而不是 id 来查找视图.

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

findViewById(R.id.someView);

但我想做这样的事情:

findViewByName("someView");

推荐答案

在处理xml的时候必须通过标识符来查找视图,但是可以使用getIdentifier(String name, ...) 例如,如果您对布局进行编号,这将很有用.请注意,这样的查找成本相对较高.

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.

完成答案

int id = getResources().getIdentifier(name, "id", context.getPackageName());
View view = findViewById(id);

这篇关于按名称查找视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆