0

I have a <Button/>

<Button
    android:id="@+id/btn"
    android:background="@drawable/btn_color"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Button background is set as android:background="@drawable/btn_color" where btn_color is

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:padding="10dp">
    <solid android:color="#FF0000"/>
    <corners android:radius="10dp"/>
</shape>

I need to get the color #FF0000 of the button in my code. What I have tried is

val drawable = btn.getBackground().mutate() as GradientDrawable

How to get the color from this Drawable?

Darrell Teague
  • 4,132
  • 1
  • 26
  • 38
Prithvi Bhola
  • 3,041
  • 1
  • 16
  • 32

3 Answers3

0

Use:

val color = (btn.background as? GradientDrawable)?.color?.defaultColor

EDIT

but getColor() only available on API 24 and above. You should check Build.VERSION.SDK_INT >= Build.VERSION_CODES.N :

val color = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    (btn.background as? GradientDrawable)?.color?.defaultColor
} else null
Akaki Kapanadze
  • 2,552
  • 2
  • 11
  • 21
  • It is throwing `java.lang.NoSuchMethodError : Method not found: MemberDescription(ownerInternalName = android/graphics/drawable/GradientDrawable, name = getColor, desc = ()Landroid/content/res/ColorStateList;, isStatic = false)` – Prithvi Bhola Aug 31 '18 at 11:06
0

Try:

val color = (btn.background as? ShapeDrawable)?.paint.color
Muzammil Husnain
  • 1,218
  • 1
  • 10
  • 24
  • `java.lang.ClassCastException: android.graphics.drawable.GradientDrawable cannot be cast to android.graphics.drawable.ShapeDrawable: Ljava/lang/ClassCastException;` exception is coming – Prithvi Bhola Aug 31 '18 at 11:04
0

Why not convert the Drawable to Bitmap (link: How to convert a Drawable to a Bitmap?) and then get the Pixel at the center of it? Could not be the fastest way but one of the most compatible (because Gradient, Color or other type of Drawable are all flattened to a compatible Bitmap and you don't need to handle these differences)

emandt
  • 2,547
  • 2
  • 16
  • 20