Mueyiwa Moses Ikomi Mueyiwa Moses Ikomi - 1 year ago 95
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download