创建一个新的颜色drawable

sta*_*cks 69 java android android-drawable colordrawable

我试图将十六进制值转换为int,以便我可以创建一个新的颜色drawable.我不确定这是否可行,但根据文档,它应该.它显然要求

public ColorDrawable(int color)

在API级别1中添加创建具有指定颜色的新ColorDrawable.

参数 color 要绘制的颜色.

所以,我的代码不起作用,因为我得到一个无效的int:"FF6666"错误.有任何想法吗?

int decode = Integer.decode("FF6666");
ColorDrawable colorDrawable = new ColorDrawable(decode);
Run Code Online (Sandbox Code Playgroud)

Enr*_*man 148

既然你在谈论十六进制,你必须从头开始,0x不要忘记不透明度.

所以基本上:0xFFFF6666

ColorDrawable cd = new ColorDrawable(0xFFFF6666);
Run Code Online (Sandbox Code Playgroud)

您还可以在/ res中创建一个新的colors.xml文件,并定义颜色如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="mycolor">#FF6666</color>
</resources>
Run Code Online (Sandbox Code Playgroud)

并简单地获得R.color.mycolor中定义的颜色

getResources().getColor(R.color.mycolor)
Run Code Online (Sandbox Code Playgroud)

  • 我需要的是`new ColorDrawable(getResources().getColor(R.color.red)))`thanks (13认同)
  • ContextCompat.getColor(getContext(),R.color.red)用于兼容 (8认同)

JpC*_*row 15

要与ContextCompat一起使用并重新使用颜色,您可以执行以下操作:

ColorDrawable colorDrawable = new ColorDrawable(ContextCompat.getColor(this, R.color.white));
Run Code Online (Sandbox Code Playgroud)


CRU*_*DER 10

它应该是这样的......

ColorDrawable cd = new ColorDrawable(0xffff6666);
Run Code Online (Sandbox Code Playgroud)

注意我使用8个十六进制数字,而不是6个十六进制数 这增加了透明度


Ber*_*ing 6

通过遵循上述建议,对这个问题做一个总结:

  1. ColorDrawable colorDrawable = new ColorDrawable( Color.parseColor ("#ce9b2c"));`

  2. ColorDrawable colorDrawable = new ColorDrawable( 0xFFCE9B2C ); 请注意,有 8 个十六进制数字,而不是 6 个十六进制数字,这不起作用。案例全部

  3. ColorDrawable colorDrawable = new ColorDrawable(ContextCompat.getColor(mContext,R.color.default_color));

由你选择!