【问题标题】:How to color button background when it is disabled禁用时如何为按钮背景着色
【发布时间】:2019-10-03 17:24:27
【问题描述】:

我想为片段中定义的按钮着色。我创建了新样式(我将其用作按钮中的主题)并为启用状态定义了“colorAccent”,为禁用状态定义了“colorButtonNormal”,并且此样式的父项是“Widget.AppCompat.Button”。当按钮被禁用时,我希望它的颜色与 colorButtonNormal 中所写的完全一致。

    <style name="Material.Button.Primary" parent="@style/Widget.AppCompat.Button">
        <item name="android:colorButtonNormal">@color/color_disabled</item>
        <item name="colorAccent">@color/color_primary</item>
    </style>
        <Button
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/button_text"
            android:textAppearance="@style/AppTheme.Text"
            android:theme="@style/Material.Button.Primary" />

当按钮启用时,它具有来自 colorAccent 的正确颜色。当用户点击它时,它会被禁用并且应该是灰色的(#b2b2b2),但它会变亮一点(#E7E7E7)。它似乎采用了我定义的颜色并与白色混合。

我尝试更改样式的父级,并对样式和按钮的属性进行了一些更改,因为它是在互联网上的一些指南中编写的,但没有任何效果。我目前的解决方案是将 colorButtonNormal 设置为#000000。当按钮被禁用时,它变为#B9B9B9。

【问题讨论】:

  • 我不知道这样做的任何属性。您可以尝试在运行时调用Button.setBackgroundTintList(null) 并检查。
  • @ADM,现在两种状态都是纯白色

标签: android android-drawable android-appcompat android-button


【解决方案1】:

如果我错了,请原谅我,但据我所知,您希望为启用/禁用状态实现不同的颜色。

更新

为了保持材质效果,您可以使用 Widget.AppCompat.Button.Colored 的样式并创建具有指定颜色的主题:

<Button
.
.
.
    style="@style/Widget.AppCompat.Button.Colored"
    android:theme="@style/CustomButton"/>

创建主题,colorButtonNormal 表示禁用状态

<style name="CustomButton" parent="Widget.AppCompat.Button.Colored">
        <item name="colorButtonNormal">@color/color_disabled</item>
        <item name="colorAccent">@color/color_enabled</item>
</style>

旧无材质效果

您可以尝试使用如下选择器:

custom_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@color/color_disabled" />
    <item android:state_enabled="true" android:drawable="@color/color_enabled/>
</selector>

然后在您的 xml 中获取按钮:

<Button
.
.
.
android:background="@drawable/custom_button" />

【讨论】:

  • 是的,我认为你在这里错了。通过覆盖android:background 按钮将失去材质效果..
  • 我已经在您修改后的答案中使用了样式和主题。它不起作用。正如我所说,当按钮被禁用时,您在 colorButtonNormal 中定义的颜色会变浅
猜你喜欢
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 2013-09-14
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
相关资源
最近更新 更多