Search code examples
javaandroidandroid-linearlayoutbackground-color

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.


Solution

  • 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.