【问题标题】:How do I get a color id with a known color name如何获取具有已知颜色名称的颜色 ID
【发布时间】:2013-08-11 05:02:24
【问题描述】:

我在/values/colors.xml 中定义了一些颜色。

如何以编程方式获取某种颜色的 id,例如R.color.my_color 如果我知道颜色的名称。

【问题讨论】:

标签: android


【解决方案1】:

我发现接受的答案不起作用,因为当我尝试设置 ImageView 的背景时,它没有设置正确的颜色。但是后来我尝试将背景设置为资源,并且效果很好。

因此,如果有任何其他混淆,我只想复制@MarcinOrlowski 的答案并将所有这些放在一起。

所以这里的函数使用反射来获取颜色的资源 id。

public int getColorByName(String name) {
    int colorId = 0;

    try {
        Class res = R.color.class;
        Field field = res.getField(name);
        colorId = field.getInt(null);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return colorId;
}

所以现在你可以通过调用这个来获取资源ID。

int resourceId = getColorByName("my_color");

当您使用此处获得的资源 ID 设置此颜色时,您需要执行此操作。

myImageView.setBackgroundResource(resourceId);

我尝试设置myImageView.setBackgroundColor(resourceId),但不起作用。

【讨论】:

    【解决方案2】:

    试试这个:

    public int getColorByName( String name ) {
        int colorId = 0;
    
        try {
            Class res = R.color.class;
            Field field = res.getField( name );
            colorId = field.getInt(null);
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    
        return colorId;
    }
    

    在你的情况下,namemy_color

    getColorByName("my_color");
    

    【讨论】:

    • 当我使用此代码时,我得到 0 作为颜色 id
    【解决方案3】:

    Resources 中有一个专用方法,称为getIdentifier
    这是实现搜索结果的“正常”方式。

    试试

    final int lMyColorId = this.getResources().getIdentifier("my_color", "color", this.getPackageName());
    

    其中thisActivity 或任何Context 子类引用。 (如果需要,请替换为 getActivity()。)
    据说这很慢,但 imo,这不应该比通过接受的答案建议的反射机制访问字段慢。

    描述了某些资源类型的使用示例here

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
    • 已更新。顺便说一句,我的回答是正确的,但不完整,你没有合法性拒绝它。特别是认为这是我在这个网站上的第一个答案,这种行为非常令人沮丧。
    • 供您参考,我没有对您投反对票。我刚刚查看了您的答案并引导您走向正确的方向。
    【解决方案4】:

    获得Context 后,您可以调用getResources()-- 以获取Resources 引用,然后查询它以获取资源的colorid

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-13
      • 2011-11-27
      • 2022-01-15
      相关资源
      最近更新 更多