2

I am setting the background of listview items in code like this:

RelativeLayout root;
root = (RelativeLayout) convertView.findViewById(R.id.root);
root.setBackgroundColor(-14774017);

This sets the background colour correctly, but at 100% opacity. I would like to set the transparency of the relativelayout background. I understand that hex-codes can have alpha values at the start in android - eg #AARRGGBB, but how would I add transparency to the background when I am using an integer colour value (for example -14774017)?

Mike Baxter
  • 6,868
  • 17
  • 67
  • 115
  • Why do you have to use an integer? Check this if you have no choice: http://stackoverflow.com/questions/6539879/how-to-convert-a-color-integer-to-a-hex-string-in-android – Yoann Hercouet Sep 16 '13 at 14:25
  • @YoannHercouet I have no choice in the matter. Thanks for the link :) – Mike Baxter Sep 16 '13 at 14:45

2 Answers2

2

The color int value contains all the alpha, red, green and blue components.

The components are stored as follows (alpha << 24) | (red << 16) | (green << 8) | blue. Each component ranges between 0..255 with 0 meaning no contribution for that component, and 255 meaning 100% contribution.

The Color class provides utility methods to extract or combine these components. The following snippet will create a color int from the user-specified color and alpha values:

int alpha = 128; //50% transparency
int color = -14774017; //Your color value
int bgColor = Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));

root.setBackgroundColor(bgColor);
Rajesh
  • 15,724
  • 7
  • 46
  • 95
0

Create a XML color resource file:

ex: /res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="list_background">#66A4C739</color>
</resources>

Then in your Fragment or Activity,

RelativeLayout root = (RelativeLayout) convertView.findViewById(R.id.root);
root.setBackgroundColor(getResources().getColor(yourpackage.R.color.list_background));

If you're not doing this in a Fragment or an Activity, you need a Context:

context.getResources().getColor(yourpackage.R.color.list_background));
Jon Willis
  • 6,993
  • 4
  • 43
  • 51