Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new color drawable

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); 
like image 429
stacksonstacks Avatar asked Oct 16 '13 15:10

stacksonstacks


People also ask

How do I make ColorDrawable?

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

How do I change the color of a drawable in xml?

Use app:drawableTint="@color/yourColor" in the xml instade android:drawableTint="@color/yourColor" . It has the backward compatibility.


2 Answers

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) 
like image 90
Enrichman Avatar answered Sep 28 '22 08:09

Enrichman


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

ColorDrawable colorDrawable = new ColorDrawable(ContextCompat.getColor(this, R.color.white)); 
like image 34
JpCrow Avatar answered Sep 28 '22 09:09

JpCrow