How do you get the background color of a button?

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

 public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        Button btn1 = findViewById(;
        //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( {
              String line = "it's red";

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

 java.lang.ClassCastException: cannot be cast to

Can anyone explain what I'm doing wrong?

Answers 1

  • 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(;
        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);

Related Articles