Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass color resource as parameter (Android)

This could be the simplest thing ever but for the life of me I haven't figured it out just yet.

I have a method that sets the background color of layout but I want to pass the color as a parameter like we do with drawable resources. eg

public void setIcon (Drawable icon){
  this.icon = context.getResources().getDrawable(icon);
}

setIcon(R.drawable.tuborg);

I want to be able to do something similar with color (R.color.id). I've tried

public void setColor (Color color){
  layout.setBackgroundColor(context.getResources().getColor(color));
}

and

public void setColor (Color color){
  layout.setBackgroundColor(ContextCompat.getColor(color));
}

both of which are asking for int, even (int color) doesn't work. Plus I'm trying to avoid Color.parse().

This is how I'm using the function

setColor(R.color.colorAccent);

I have an xml with various color codes. I want to be able just call this function and get the background color change.

like image 906
Mueyiwa Moses Ikomi Avatar asked Nov 23 '16 18:11

Mueyiwa Moses Ikomi


2 Answers

You can try this out:

public void setColor (int colorId){
  layout.setBackgroundColor(ContextCompat.getColor(colorId));
}

In that method colorId should be an hexa code of the color

A good practice is to define the color on colors.xml (inside values folder).

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <color name="red">#FF0000</color>
</resources>

In this case, you will use this function like this:

setColor(R.color.red);

So, there is no need to create a "color" object, you can pass values from colors.xml

Also, in your case you should modify the method setColor(Color aColor) to setColor(int aColor) to make it work with the xml color resource.

like image 88
shollmann Avatar answered Sep 25 '22 17:09

shollmann


You need a color resource id. It starts with R.color which is actually an integer id.

public void setColor (@ColorInt int colorId){ // integer id 
  layout.setBackgroundColor(ContextCompat.getColor(colorId));
}

UPDATE

Although you are using it like setColor(R.color.colorAccent) but still your function parameter expects a color e.g.

setColor (Color color)

. You need to update the function parameter type to int, like I did in the above snippet.

setColor (int color)

Also from the docs of ContextCompat.getColor.

Returns a color associated with a particular resource ID.Starting in {@link android.os.Build.VERSION_CODES#M}, the returned color will be styled for the specified Context's theme.

@param id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.

@return A single color value in the form 0xAARRGGBB.

like image 37
mallaudin Avatar answered Sep 26 '22 17:09

mallaudin