选择器可在 MaterialButton android 上绘制

Muh*_*lib 7 android material-design

我一直在使用新的 MaterialButton 类。当用户单击按钮时,我希望按钮上有不同的颜色。

从一开始我就一直为此目的使用选择器可绘制对象,但是它似乎不适用于 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"
Run Code Online (Sandbox Code Playgroud)

/>

我的 Widget.Mohre.Button 样式

<style name="Widget.Mohre.Button" parent="Widget.MaterialComponents.Button">
        <item name="android:textColor">@color/textColorWhite</item>
        <item name="android:background">@drawable/mohre_button_selector</item>
        <item name="android:textAppearance">@style/TextAppearance.Button</item>
        <item name="android:stateListAnimator" tools:ignore="NewApi">@animator/button_state_list_anim</item>
    </style>
Run Code Online (Sandbox Code Playgroud)

我的选择器可绘制

<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" />
Run Code Online (Sandbox Code Playgroud)

我的个人可绘制对象只是具有不同颜色的矩形形状,例如

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <corners android:radius="30dp"></corners>
    <solid android:color="#3a516a"></solid>
</shape>
Run Code Online (Sandbox Code Playgroud)

该按钮根本不采用选择器可绘制的颜色。它只显示应用程序的默认强调色

ake*_*lec 0

如果您想要一个具有自定义背景的按钮(例如应用<selector>),但您的主题设置为使用Theme.MaterialComponents(现在是 2021 年),您可以将布局中的 XML 元素切换<android.widget.Button><Button>. 这应该会导致 Android 的 Material Components 忽略该元素,并且您可以根据 XML 属性正常操作该按钮。