Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set theme for AppCompatButton programmatically

I have a button that have two state and must have different background for each of them.

For using advantage of android default implement of Button (for example ripple effect in +Lollipop) i didn't define custom background and using colorButtonNormal attribute as below :

<style name="PrimaryButton.Success">
  <item name="colorButtonNormal">@color/colorSuccess</item>
</style>

<style name="PrimaryButton.Fail">
  <item name="colorButtonNormal">@color/colorFail</item>
</style>

I know how to set theme for my button when using XML(setting app:theme attribute of my AppCompatButton) but as i mention above,I need change it on run-time programmatically. how can i do it ?


1 Answers

If you only need one color at a time (in spite of the state), you can use

Button button = ...;
int color = ...;
ViewCompat.setBackgroundTintList(button, ColorStateList.valueOf(color));

This will preserve ripple effect on Lollipop and newer devices (API 21+)

like image 99
zarsky Avatar answered Dec 06 '25 07:12

zarsky