3

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 ?

Mojtaba Asgari
  • 1,242
  • 1
  • 13
  • 24
  • 1
    Possible duplicate of [How to programmatically setting style attribute in a view](http://stackoverflow.com/questions/2016249/how-to-programmatically-setting-style-attribute-in-a-view) – OneCricketeer Jun 16 '16 at 14:13
  • @MojtabaAsg Are you sure you want to change the theme? Why not set the color of the button to a [Color State List](https://developer.android.com/guide/topics/resources/color-list-resource.html)? – Bryan Jun 16 '16 at 14:15
  • @cricket_007 no my question is about new attribute added to appcompatbutton and not legacy style ! – Mojtaba Asgari Jun 16 '16 at 14:44
  • @Bryan let me know your approach, can i define custom state and change state with your solution ? – Mojtaba Asgari Jun 16 '16 at 14:47

1 Answers1

4

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+)

zarsky
  • 680
  • 2
  • 14
  • 24