2

I have researched before asking this but suggested answers have not worked for me.

I have a bunch of colors listed in my colors.xml file like below:

<color name="material_red">#F44336</color>
<color name="material_orange">#FF5722</color>
<color name="material_yellow">#FFC107</color>

and in my main layout, have applied one to the background as below:

<RelativeLayout
 ….
 android:background="@color/material_blue"/>

I need to get the exact type of color that the layout is programmatically, this is what I've tried so far:

RelativeLayout relativeLayout = findViewById(…);
Drawable layoutDrawable = relativeLayout.getBackground();

String layoutColor;
if(layoutDrawable instanceOf ColorDrawable){
     int color = ((ColorDrawable)layoutDrawable).getColor(); 
     layoutColor = Integer.toHexString(color); 
}

However the result comes to something like this: ff2196f3.

How can I get the color in exact HEX value or possibly the color resource that was applied?

Boron
  • 99
  • 10
  • 34

4 Answers4

0

ff2196f3 is almost exactly what you want excluding first byte, which are responsible for the opacity. This way your color is 2196f3 + ff is it's opacity.


You can't get the color resource, because it doesn't have to be the color resource, it can be set dynamically without the color resource. But if you want, you can iterate through the color resources comparing them to what you got.

Vladyslav Matviienko
  • 10,610
  • 4
  • 33
  • 52
0

Try this,

String hexColor = "#" + layoutColor.substring(2, layoutColor.length());
Log.e("MainActivity.java", "The hex color is-" + hexColor);
Shahbaz A.
  • 4,047
  • 4
  • 34
  • 55
jibs
  • 3
  • 1
  • 5
0

This is most likely a duplicate and has been already answered here.

Android color ints are most common representation of colors on Android and according the documentation it always defines a color in the sRGB space using 4 components: Alpha, Red, Green, Blue. So the first two digits in your string are Alpha channel. However, as suggested by @Josh, you can get the last 6 digits by masking:

if(layoutDrawable instanceof ColorDrawable){
    int color = ((android.graphics.drawable.ColorDrawable)layoutDrawable).getColor();
    layoutColorWithoutAlpha = String.format("#%06X", (0xFFFFFF & color));
}
hsallajo
  • 1
  • 1
-1

To get background color of a Layout:

LinearLayout lay = (LinearLayout) findViewById(R.id.lay1);
ColorDrawable viewColor = (ColorDrawable) lay.getBackground();
int colorId = viewColor.getColor();

If It is RelativeLayout then just find its id and use there object instead of LinearLayout.

Imran khan
  • 123
  • 1
  • 12