我在/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;
}
在您的情况下name
my_color
:
getColorByName("my_color");
Resources
中有一个专用的方法叫做getIdentifier
。
这是实现您搜索内容的"正常"方式。
尝试
final int lMyColorId = this.getResources().getIdentifier("my_color", "color", this.getPackageName());
其中this
是Activity
或任何Context
子类引用。(如果需要,请替换为getActivity()
。
据说这很慢,但恕我直言,这不应该比通过公认的答案所暗示的反射机制访问字段慢。
此处介绍了某些资源类型的使用示例。
一旦你有了Context
,你就可以调用getResources()
- 获取Resources
引用,然后查询它以获取资源的color
和id
。
我发现接受的答案不起作用,因为当我尝试设置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;
}
因此,现在您只需调用 this 即可获取资源 ID。
int resourceId = getColorByName("my_color");
当您使用此处的资源 ID 设置此颜色时,您需要执行此操作。
myImageView.setBackgroundResource(resourceId);
我尝试设置myImageView.setBackgroundColor(resourceId)
但不起作用。