I'd like to change the color of a standard Android button slightly in order to better match a client's branding.
The best way I've found to do this so far is to change the Button
's drawable to the drawable located in res/drawable/red_button.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/red_button_pressed" />
<item android:state_focused="true" android:drawable="@drawable/red_button_focus" />
<item android:drawable="@drawable/red_button_rest" />
</selector>
But doing that requires that I actually create three different drawables for each button I want to customize (one for the button at rest, one when focused, and one when pressed). That seems more complicated and non-DRY than I need.
All I really want to do is apply some sort of color transform to the button. Is there an easier way to go about changing a button's color than I'm doing?
If you are making colour buttons with XML you can make the code a bit cleaner by specifying the focused and pressed state in a separate file and reuse them. My green button looks like this:
I am using this approach
style.xml
As you can see from above, I'm using a custom style for my button. The button color corresponds to the accent color. I find this a much better approach than setting
android:background
as I won't lose the ripple effect Google provides.Following on from Tomasz's answer, you can also programmatically set the shade of the entire button using the PorterDuff multiply mode. This will change the button colour rather than just the tint.
If you start with a standard grey shaded button:
will give you a red shaded button,
will give you a green shaded button etc., where the first value is the colour in hex format.
It works by multiplying the current button colour value by your colour value. I'm sure there's also a lot more you can do with these modes.
You can Also use this online tool to customize your button http://angrytools.com/android/button/ and use
android:background="@drawable/custom_btn"
to define the customized button in your layout.The way I do a different styled button that works quite well is to subclass the Button object and apply a colour filter. This also handles enabled and disabled states by applying an alpha to the button.
The shortest solution which is working with any Android version:
Notes/Requirements:
app:
namespace and not theandroid:
namespace!appcompat version > 24.2.0
dependencies { compile 'com.android.support:appcompat-v7:25.3.1' }
Explanation: