【问题标题】:Find view by name按名称查找视图
【发布时间】:2011-07-26 14:20:58
【问题描述】:

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

findViewById(R.id.someView);

但我想做这样的事情:

findViewByName("someView");

【问题讨论】:

标签: android android-layout


【解决方案1】:

在处理 xml 时,您必须按标识符查找视图,但您可以使用 getIdentifier(String name, ...) 查找标识符,例如,如果您对布局进行编号,这很有用。请注意,这样的查找相对昂贵。

完成答案

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

【讨论】:

    【解决方案2】:

    是的,我们也可以通过名称找到任何静态资源。

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

    getResources().identifier 将在资源未找到或名称不匹配时始终返回 0。

    【讨论】:

    • 这与@MrJre 的回答有何不同? ...不要让网站因重复而混乱。
    猜你喜欢
    • 2013-04-26
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 2021-05-17
    • 2018-04-15
    • 1970-01-01
    相关资源
    最近更新 更多