How do you get the background color of a button?

672 Views Asked by At

How do you get the background color of a button? I've tried the following:

 public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn1 = findViewById(R.id.button);
        btn1.setBackgroundColor(getResources().getColor(R.color.red));
        //color red is added to colors.xml <color name="red">#FF0000</color>

        btn1.setOnClickListener(v -> {

          ColorDrawable btnColor = (ColorDrawable) btn1.getBackground();

          int clr = btnColor.getColor();

          if (clr == getResources().getColor(R.color.red)) {
              String line = "it's red";
              btn1.setText(line);
            }
        });
    }
}

When I click the button the app closes and I get this

 java.lang.ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable

Can anyone explain what I'm doing wrong?

3

There are 3 best solutions below

1
Gabriele Mariotti On BEST ANSWER

Since you are using a MaterialComponents theme your Button is replaced at runtime by a MaterialButton.

Use the setBackgroundTintList instead of the setBackgroundColor and use getBackgroundTintList() to retrieve the ColorStateList.

Something like:

    MaterialButton button = findViewById(R.id.button);
    button.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.red600)));
    ColorStateList colorStateList = button.getBackgroundTintList();

    int defaultColor = colorStateList.getColorForState(
            new int[] { android.R.attr.state_enabled},0);
2
Suraj Pendhare On
ColorDrawable buttonColor = (ColorDrawable) button.getBackground();
int colorId = buttonColor.getColor();
if (colorID == R.color.green) {
  log("color is green");
}

Using the above you can find a button color.

1
Hassan On

you can get this as a drawable:

Button mButton = (Button) findViewById(R.id.button);
Drawable buttonBackground = mButton.getBackground();

if its a color you can do like this:

ColorDrawable btnColor = (ColorDrawable) button.getBackground();

get out resource id of the color:

Int color = btnColor.getColor();

then compare this with your color:

if (color == R.color.green) {
   log("color is green");
}