Search code examples
androidandroid-viewandroid-buttonandroid-themeandroid-styles

Change Button's enabled color without changing disabled color


I'm using the element Button for my xml layout. Button class from android.widget that extends TextView.

This view has a possibility to tag as enable or disable by java code. .setEnabled(true|false).

Button xml code

<Button
    android:id="@+id/maps_list_save_button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="@string/str_save"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

What I wanna:

enter image description here When my button is enable I wanna give him a purple color.

enter image description here When my button is disable get a grey color.

What I don't wanna do:

Create a new element and include the layout, I'm avoiding this because I wanna keep the selected animation, raise, padding, elevation etc. Create everything again is not smart.

What I already try:

Change the Background = it loose the inside padding, what make the button bigger and I wanna keep the material design "rules" enter image description hereenter image description here

Change Theme = I tried to change the theme, by editor and by code but two things happen: or I change more stuffs that are not the button or I change the Enable and Disable for the same color.

Even looking for the docs I did not found how to use properly this element.


Solution

  • What you need is to change android:colorAccent value for specifically that Button. That can be achieved with applying a theme to the Button.

    Inside styles.xml introduce following changes:

    <style name="PurpleTheme" parent="AppTheme">
        <item name="android:colorAccent">#8654e2</item>
    </style>
    

    Then declare following two buttons in the xml file, where first button has enabled state, and second button has disabled state.

    <Button
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1"
        android:theme="@style/PurpleTheme" />
    
    <Button
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:text="Button 2"
        android:theme="@style/PurpleTheme" />
    

    Pay attention, that buttons are applied:

    • style="@style/Widget.AppCompat.Button.Colored"
    • android:theme="@style/PurpleThemeOverlay"

    Then you'll get following output:

    enter image description here