Home > Enterprise >  Unable to get button background color
Unable to get button background color

Time:11-24

I am trying to obtain the current background color of a button from a randomized color palette. However, my app is always crashing when I try the following code.

int activeColor = ((ColorDrawable)color1.getBackground()).getColor();

I always get this error message.

    Process: com.boredgiant.chora, PID: 17418
    java.lang.ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable
        at com.boredgiant.chora.DrawActivity$103.onClick(DrawActivity.java:850)
        at android.view.View.performClick(View.java:6314)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
        at android.view.View$PerformClick.run(View.java:24793)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6543)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)

CodePudding user response:

You need to cast it to RippleDrawable

int activeColor = ((RippleDrawable)color1.getBackground()).getColorStateList().getDefaultColor();
  • Related