How do I set the disabled color of a button with AppCompat?

Viewed 52077

I use this style to change the background color of my Button:

<style name="AccentButton" parent="Widget.AppCompat.Button.Colored">
    <item name="colorButtonNormal">@color/colorAccent</item>
    <item name="android:textColor">@color/white</item>
</style>

And in layout:

    <Button
        android:id="@+id/login_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/fragment_login_login_button"
        app:theme="@style/AccentButton"/>

It works. But when I call setEnabled(false) on this Button, it keeps the same color. How can I manage this case?

7 Answers

Currently, I use the following settings for Android API 15+.

/res/color/btn_text_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="#42000000" android:state_enabled="false" />
  <item android:color="#ffffff" />
</selector>

/res/values/styles.xml

<style name="ColoredButton" parent="Widget.AppCompat.Button.Colored">
    <item name="android:textColor">@color/btn_text_color</item>
</style>

and

<Button
    android:id="@+id/button"
    style="@style/ColoredButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="button" />

Complete solution extending from ianhanniballake' answer and Joe Bowbeer' comment:

/res/values/styles.xml

<style name="AccentButton" parent="ThemeOverlay.AppCompat.Dark">
    <!-- customize colorAccent for the enabled color -->
    <!-- customize colorControlHighlight for the enabled/pressed color -->
    <!-- customize colorButtonNormal for the disabled color -->
    <item name="android:buttonStyle">@style/Widget.AppCompat.Button.Colored</item>
</style>

And wherever you use the button:

<Button
    android:id="@+id/login_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/fragment_login_login_button"
    android:theme="@style/AccentButton"/>

That worked really nice for me

Kotlin implementation of @meanman's answer above, adjusting alpha is by far the simplest way to go and all my touch ripple effects still work as before:

import android.content.Context
import android.support.v7.widget.AppCompatButton
import android.util.AttributeSet

class FadedDisableButton : AppCompatButton {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun setEnabled(enabled: Boolean) {
        alpha = when {
            enabled -> 1.0f
            else -> 0.5f
        }
        super.setEnabled(enabled)
    }
}
Related