Create a new color drawable

时光总嘲笑我的痴心妄想 提交于 2019-12-31 08:26:37

问题


I am trying to convert a hex value to an int so I can create a new color drawable. I'm not sure if this is possible, but according to the documentation, it should. It plainly asks for

public ColorDrawable (int color)

Added in API level 1 Creates a new ColorDrawable with the specified color.

Parameters color The color to draw.

So, my code isn't working because I'm getting an Invalid int: "FF6666" error. Any ideas?

int decode = Integer.decode("FF6666");
ColorDrawable colorDrawable = new ColorDrawable(decode);

回答1:


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)



回答2:


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

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



回答3:


It should be like this...

ColorDrawable cd = new ColorDrawable(0xffff6666);

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




回答4:


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




回答5:


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!




回答6:


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


来源:https://stackoverflow.com/questions/19407672/create-a-new-color-drawable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!