3

I need to know what is the best (and recommented) way to tint a Material Button (AppCompatButton) using the latest AppCompat (23.2.1 for the time being). I could have never imagined that it would be so frustrating! I tried most of the answers from here but either they wouldn't work or worked with unexpected results.

I need to keep backwards compatibility to api >= 9 And just need the ripple effect to be applied to >=21 nothing fancy. So what is the best way so far?

I'd appreciate if you could provide both xml and java code.

Community
  • 1
  • 1
ThanosFisherman
  • 5,626
  • 12
  • 38
  • 63

1 Answers1

12

There are many ways to do that. My favorite is the following:

<Button
 android:id="@+id/activity_main_some_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 style="@style/Widget.AppCompat.Button.Colored"
 android:text="This is a button" />  

This automatically tints the button with the accent color you (hopefully) set in your theme, while maintaining pressed states at API < Lollipop and Ripple >= Lollipop.

If nothing else works you could just tint the button yourself:

AppCompatButton myExampleButton = new AppCompatButton(getContext());

myExampleButton.setSupportBackgroundTintList(ContextCompat.getColorStateList(getContext(),
                                             R.color.some_color));

Update

You can do the following to use a self defined color:

<style name="MyButtonTheme" parent="Widget.AppCompat.Button.Colored">
    <item name="colorButtonNormal">@color/someColor</item>
</style>

Define a new style with the desired color.

<Button
 android:id="@+id/activity_main_some_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:theme="@style/MyButtonTheme"
 android:text="This is a button" />

Set it to your button.

rubengees
  • 1,841
  • 2
  • 16
  • 31