Android: How To Change Android Button Color


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

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

Case Button Disabled

Use View.setAlpha

button.alpha = if (button.isEnabled) 1f else 0.5f

Source: https://code.luasoftware.com/tutorials/android/change-android-button-color-while-maintain-effect-and-state-color/

Leave a Reply