5

First, I set the green color to be the background of the View mIcon,

View mIcon = findViewById(R.id.xxx);

GradientDrawable gdraw = (GradientDrawable) mContext.getResources().getDrawable(R.drawable.roundbtn_white_normal);
gdraw.setColor(Color.GREEN);
mIcon.setBackgroundDrawable(gdraw);

Then, I don't know how to get the color from this View's background... there's no getColor() function...

shanwu
  • 1,111
  • 6
  • 32
  • 43

3 Answers3

4

the following class works fine for me so far.

import android.content.res.Resources;
...

// it's the same with the GradientDrawable, just make some proper modification to make it compilable
public class ColorGradientDrawable extends Drawable {
    ...
    private int mColor; // this is the color which you try to get
    ...
    // original setColor function with little modification
    public void setColor(int argb) {
        mColor = argb;
        mGradientState.setSolidColor(argb);
        mFillPaint.setColor(argb);
        invalidateSelf();
    }

    // that's how I get the color from this drawable class
    public int getColor() {
        return mColor;
    }
    ...

    // it's the same with GradientState, just make some proper modification to make it compilable
    final public static class GradientState extends ConstantState {
        ...
    }
}
shanwu
  • 1,111
  • 6
  • 32
  • 43
3

getColor() API is added to the gradient drawable class in API 24.

https://developer.android.com/reference/android/graphics/drawable/GradientDrawable.html

Varun Bhatia
  • 4,226
  • 30
  • 41
0

This can only be accomplished in API 11+ if your background is a solid color. It's easy to get this as a Drawable

Drawable mIconBackground = mIcon.getBackground();         
if (mIconBackground instanceof ColorDrawable)
            color = ((ColorDrawable) background).getColor();

And if you're on Android 3.0+ you can get out the resource id of the color.

int colorId = mIcon.getColor();

And compare this to your assigned colors, ie.

if (colorId == Color.GREEN) {
  log("color is green");
}

Hope this will help you.

khurram
  • 1,362
  • 12
  • 24