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

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

最佳答案

尝试这个:

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");

关于android - 如何获得具有已知颜色名称的颜色ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18143713/

10-11 22:27
查看更多