创建一个新的可绘制颜色

我试图转换一个十六进制值为整型,以便我可以创建一个新的颜色绘制。我不确定这是否可行,但根据 文件,应该可行。它明显要求

Public ColorDrawable (int color)

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

参数 颜色要绘制的颜色。

因此,我的代码无法工作,因为我得到了一个无效的 int: “ FF6666”错误。有什么办法吗?

int decode = Integer.decode("FF6666");
ColorDrawable colorDrawable = new ColorDrawable(decode);
110954 次浏览

Since you're talking about hex you have to start with 0x and don't forget the opacity.

So basically: 0xFFFF6666

ColorDrawable cd = new ColorDrawable(0xFFFF6666);

You can also create a new colors.xml file into /res and define the colors like:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="mycolor">#FF6666</color>
</resources>

and simply get the color defined in R.color.mycolor

getResources().getColor(R.color.mycolor)

I think you have to use :

public static int parseColor (String colorString)

Added in API level 1 Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray, darkgray, grey, lightgrey, darkgrey, aqua, fuschia, lime, maroon, navy, olive, purple, silver, teal

It should be like this...

ColorDrawable cd = new ColorDrawable(0xffff6666);

Note I used 8 hex digits, not 6 hex digit . which add to transparency

For using with ContextCompat and rehuse the color you can do something like this:

ColorDrawable colorDrawable = new ColorDrawable(ContextCompat.getColor(this, R.color.white));

By followingthe above advice,to be a summary of this question:

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

  2. ColorDrawable colorDrawable = new ColorDrawable(0xFFCE9B2C); Note there is 8 hex digits, not 6 hex digit,which no work. Case all

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

Selecting up to you!

This is how I converted a Hex color to int and applied to a Background of a View

Let's say that we have a color #8080000.

1) Hex to int conversion

int myColor = Color.parseColor("#808000");

2) Set background

view.setBackgroundColor(context.getColor(myColor));

Xamarin/Maui :

  protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);


Window.SetBackgroundDrawable(new ColorDrawable(ColorExtensions.ToAndroid(Colors.Black)));
}