Mueyiwa Moses Ikomi Mueyiwa Moses Ikomi - 6 months ago 49
Android Question

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.

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


i want to be able to do something similar with color ( i've tried

public void setColor (Color color){


public void setColor (Color color){

both of which are asking for int, even (int color) doesn't work. Plus i'm trying to avoid Color.parse(). Any alternative is appreciated. Thanks

Hi guys, this is how i'm using the function


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


You can try this out:

public void setColor (int 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"?>
    <color name="red">#FF0000</color>

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


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.