Best Way To Change Android Button Color While Maintain Effect And State Color

April 17, 2018
Use backgroundTint

I find changing button color is one of the most difficult things to do right in Android when I first started programming for Android 2.2 (API Level 8). Thankfully, things are slightly better now.

android:background

Don’t use android:background, as it will replace the entire Drawable thus removing click effect (e.g. material ripple effect) and remove changing of color state when pressed.

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    />

android:theme

Some suggested create a color theme, but I find it too troublesome and not flexible.

Edit res/values/styles.xml to create a button theme with specific color.

<style name="Button.White" parent="ThemeOverlay.AppCompat">
    <item name="colorAccent">@android:color/white</item>
</style>

Apply android:theme to your button.

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/Button.White"
    />

backgroundTint

My personal favourite is backgroundTint.

If you are targetting API Level 21 and higher, you can use android:backgroundTint.

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:backgroundTint="@android:color/white"
    />

For API Level 7 and higher, you should use app:backgroundTint.

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:backgroundTint="@android:color/white"
        />

</android.support.constraint.ConstraintLayout>

If you need to set the button backgroundTint programatically.

ViewCompat.setBackgroundTintList(button, ContextCompat.getColorStateList(this, android.R.color.white))

To handle color state when button is disabled, refer to Android Button Disabled Color Not Working After Color Change.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.