Search code examples
androidmaterial-designandroid-stylesmaterial-components-androidmaterial-components

Can't set backgound color of button changing state_enabled


I have a field for entering a phone number and mask for it. I want the button color to be, for example, black when the mask is not yet fully filled, and yellow when it is filled.

My button

<Button
    android:id="@+id/buttonNext"
    style="@style/AppTheme.YellowButton"
    android:text="Далее"/>

Style

<style name="AppTheme.YellowButton" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="android:textSize">@dimen/text_size_20sp</item>
    <item name="android:textColor">@color/color_accent</item>
    <item name="android:textAllCaps">false</item>
    <item name="android:textStyle">bold</item>
    <item name="android:backgroundTint">@color/yellow_mail</item>
    <item name="android:drawable">@color/selector_colored_button</item>
</style>

@color/selector_colored_button

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:color="@color/yellow_mail"/>
    <item android:state_enabled="false" android:color="@android:color/black"/>
</selector>

And code for it

MaskedTextChangedListener.installOn(
    editText = editPhone,
    primaryFormat = "[000] [000]-[00]-[00]",
    valueListener = object : MaskedTextChangedListener.ValueListener {
        override fun onTextChanged(
            maskFilled: Boolean,
            extractedValue: String,
            formattedValue: String
        ) {
            buttonNext.isEnabled = maskFilled
        }
    })

But the button is yellow all the time, its background does not change. Not sure what I'm doing wrong. Any help? I'm using "com.google.android.material:material:1.2.0-alpha06" and Theme.MaterialComponents.DayNight.NoActionBar


Solution

  • Remove this line:

    <item name="android:drawable">@color/selector_colored_button</item>
    

    and use:

    <item name="android:backgroundTint">@color/selector_colored_button</item>
    

    you can look my answer