How to get color from GradientDrawable

First I set green as the background for 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 do not know how to get the color from this background view ... there is no getColor () function ...

+5
source share
3 answers

the next class has been working fine for me so far.

 import android.content.res.Resources; ... // it 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 how I get the color from this drawable class public int getColor() { return mColor; } ... // it the same with GradientState, just make some proper modification to make it compilable final public static class GradientState extends ConstantState { ... } } 
+4
source

The getColor () API is added to the gradient-suitable class in API 24.

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

+2
source

This can only be done in API 11+ if your background is solid color. Easy to get it like drawable

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

And if you are on Android 3.0+, you can exit the color resource identifier.

 int colorId = mIcon.getColor(); 

And compare this to the assigned colors, i.e.

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

Hope this helps you.

+1
source

Source: https://habr.com/ru/post/1205251/


All Articles