Changing AppCompatButton color programmatically

Support Library 22.1 introduced a new AppCompatButton that should be knowledgeable and a new DrawableCompat class to set the hue of the drawable.

I just thought I needed to easily create colored buttons and programmatically change the button color.

I create a button in code, retrieve the background image from it and try to color it with a new DrawableCompat class, and then return it to the button.

AppCompatButton btn = new AppCompatButton(context);

Drawable tintDr = DrawableCompat.wrap(btn.getBackground());

DrawableCompat.setTint(tintDr, Color.BLUE);



As a result, on Android 5.x, the button is blue, but the ripple effect is lost and the button press looks rather strange. On Android <5.0, the button is gray.

How can I press a button programmatically on all android versions?


source to share

All Articles