【问题标题】:How to Override material design statepressed in for Android Button如何覆盖 Android Button 中的材料设计 statepressed
【发布时间】:2021-05-12 17:17:48
【问题描述】:

学识渊博的朋友们,

我正在使用 Material Design 主题,但我需要覆盖它的 statePressed 以便在单击按钮时它会改变颜色(突出显示片刻),如下所示。

为此,我在按钮上设置了一个可绘制对象,如下所示

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="false">
    <shape>
        <solid android:color="@color/primaryColor" />
        <stroke android:color="@color/primaryDarkColor" android:width="@dimen/stroke_width"/>
        <corners android:radius="@dimen/corner_radius" />

    </shape>

</item>


<item android:state_pressed="true">
    <shape>
        <solid android:color="@color/secondaryColor" />
        <stroke android:color="@color/secondaryLightColor" android:width="@dimen/stroke_width" />
        <corners android:radius="@dimen/corner_radius" />

    </shape>

</item>

我还有一个 ThemeOverlay 来覆盖按下状态

    <style name="ThemeOverlay.Red.UnitedStates" parent="">
<item name="android:colorPressedHighlight">@color/secondaryColor</item>
    </style>

不幸的是,当我单击按钮时,突出显示没有发生。

我可能会错过什么?

这是材料主题 XML

 <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/primaryColor</item>
    <item name="colorPrimaryVariant">@color/primaryLightColor</item>
    <item name="colorPrimaryDark">@color/primaryDarkColor</item>

【问题讨论】:

  • 你如何将drawable应用到按钮上?作为背景可绘制?另外,您如何将 ThemeOverlay 附加到您的应用程序主题?注意:您的选择器代码似乎不正确,默认状态(未按下)应始终位于底部。所以你应该把 state_pressed 放在 default 之前。检查此链接:stackoverflow.com/questions/14023886/android-button-selector

标签: android android-button android-theme material-components-android


【解决方案1】:

您可以只使用app:backgroundTint 属性:

     <com.google.android.material.button.MaterialButton
          app:backgroundTint="@color/custom_button_selector"
          ../>

与:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/red600" android:state_pressed="true"/>
    <item android:color="?attr/colorPrimary" android:state_enabled="true"/>
    <item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
</selector>

正常状态:

按下状态:

【讨论】:

  • 嗨@Gabriele,您的解决方案非常完美,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 2017-05-19
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 2020-10-26
  • 1970-01-01
相关资源
最近更新 更多