有没有办法从颜色资源中获取color-int?我试图获取资源(R.color.myColor)中定义的颜色的单个红色,蓝色和绿色组件,以便我可以将三个搜索栏的值设置为特定级别 .
有关可能有助于在搜索结果中显示此问题的另一个用例的更多信息,我想将alpha应用于我的资源中定义的颜色 .
使用@ sat的正确答案:
int alpha = ... // 0-255, calculated based on some business logic
int actionBarBackground = getResources().getColor(R.color.actionBarBackground);
int actionBarBackgroundWithAlpha = Color.argb(
alpha,
Color.red(actionbarBackground),
Color.green(actionbarBackground),
Color.blue(actionbarBackground)
);
6 回答
从非活动类访问颜色可能很困难 . 我找到的替代方案之一是使用
enum
.enum
提供了很大的灵活性 .您可以使用:
在这里查看如何定义自定义颜色:
http://sree.cc/google/android/defining-custom-colors-using-xml-in-android
EDIT(1): 由于
getColor(int id)
现在为 deprecated ,因此必须使用:(在支持库23中添加)
EDIT(2):
以下代码可用于棉花糖前后(API 23)
基于新的 Android Support Library (和this更新),现在您应该致电:
根据documentation:
此方法在 API level 23 中已弃用 . 请改用getColor(int,Theme)
它与
getResources().getColorStateList(id)
的解决方案相同:你必须改变它:
定义颜色
值/ color.xml
获取颜色int并进行设置
另见
How to set background color of a View
Color docs
Color Style Design docs
我更新使用
ContextCompat.getColor(context, R.color.your_color);
但有时(在某些设备/ Android版本上 . 我不确定)导致NullPointerExcepiton .因此,为了使它适用于所有设备/版本,我会回到旧的方式,在空指针的情况下 .
最佳方法
正如@sat的回答,获得色彩的好方法是
当您无法访问
getResources()
方法时,请使用以下方法 .我做的是什么
It is most simple to use anywhere in your app! Even in Util class or any class where you don't have Context or getResource()
问题(当你没有上下文时)
当 you don't have Context access 时,就像
Util
类中的方法一样 .假设没有Context的下面的方法 .
现在,您将在此方法中将
Context
作为参数传递并使用getResources().
所以这是一个 Bonus unique solution ,你可以通过它来访问像
Util class
这样的任何地方的资源 . 将Resources
添加到Application
类或如果不存在则创建一个 .将名称字段添加到
manifest.xml
<application
标记 . (如果尚未添加)现在你很高兴 . 在应用中的任何位置使用
ResourcesCompat.getColor(App.getRes(), R.color.your_color, null);
.