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 {

    @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?

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

Related Articles