Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selector drawable on MaterialButton android

I have been using the new MaterialButton class. I want different colors on the button when the user clicks the button.

I have been using selector drawables for this purpose since the very beginning, however it doesn't appear to be working on MaterialButton.

<com.google.android.material.button.MaterialButton
  android:layout_width="0dp" 
  android:text="@string/login"
  style="@style/Widget.Mohre.Button"
  android:layout_height="wrap_content"
  app:cornerRadius="@dimen/card_corner_radius"
  android:padding="@dimen/unit_large"
  android:id="@+id/loginBtn"/>

My Widget.Mohre.Button style

@color/textColorWhite @drawable/mohre_button_selector @style/TextAppearance.Button @animator/button_state_list_anim

My selector drawable

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/mohre_button_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/mohre_button_selected" android:state_enabled="false" android:state_pressed="false" />
<item android:drawable="@drawable/mohre_button_normal" />

My individual drawables are just rectangle shapes with different colors like these

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <corners android:radius="30dp"></corners>
    <solid android:color="#3a516a"></solid>
</shape>

The button doesn't take on the colors at all from the selector drawable. It just shows the default accent color of the application

like image 493
Muhammad Ahmed AbuTalib Avatar asked May 12 '19 06:05

Muhammad Ahmed AbuTalib


1 Answers

With the normal way (setting the selector drawable as background of the button), it won't work as expected if you are using Theme.MaterialComponents.

You can use Theme.MaterialComponents.DayNight.NoActionBar as an alternative, but if you don't want to use that theme, then simply use:

<androidx.appcompat.widget.AppCompatButton
................/>

You will get the same result as it was working with the Appcompat theme even if you are using latest Material themes!

like image 141
Dev4Life Avatar answered Oct 21 '22 03:10

Dev4Life