Mueyiwa Moses Ikomi Mueyiwa Moses Ikomi - 15 days ago 7
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);
}

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(). Any alternative is appreciated. Thanks

Hi guys, 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.

Answer

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.