如何使用 AppCompat 设置按钮的禁用颜色?

新手上路,请多包涵

我使用这种样式来更改我的 Button 的背景颜色:

 <style name="AccentButton" parent="Widget.AppCompat.Button.Colored">
    <item name="colorButtonNormal">@color/colorAccent</item>
    <item name="android:textColor">@color/white</item>
</style>

在布局中:

     <Button
        android:id="@+id/login_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/fragment_login_login_button"
        app:theme="@style/AccentButton"/>

有用。但是当我在这个 Button setEnabled(false) 时,它保持相同的颜色。我该如何处理这个案子?

原文由 Alexandr 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 700
2 个回答

您没有正确使用 Widget.AppCompat.Button.Colored 样式。您正在使用父样式 ( Widget.AppCompat.Button.Colored ),但将其用作主题。这实际上意味着 Widget.AppCompat.Button.Colored 部分被完全忽略,而您只是更改按钮的默认颜色(有效,但不处理禁用的情况)。

相反,您应该使用 ThemeOverlay 并分别应用 Colored 样式:

 <style name="AccentButton" parent="ThemeOverlay.AppCompat.Dark">
   <!-- customize colorButtonNormal for the disable color -->
   <!-- customize colorAccent for the enabled color -->
</style>

<Button
    android:id="@+id/login_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/fragment_login_login_button"
    android:theme="@style/AccentButton"
    style="@style/Widget.AppCompat.Button.Colored"/>

正如 这个关于使用 Widget.AppCompat.Button.Colored 风格的答案 中提到的,禁用颜色由 colorButtonNormal 控制,启用颜色由 colorAccent 控制通过使用 ThemeOverlay.AppCompat.DarktextColor 会自动更改为深色,这意味着您可能根本不需要自定义 ThemeOverlay

原文由 ianhanniballake 发布,翻译遵循 CC BY-SA 3.0 许可协议

不要为你的按钮使用颜色,你应该使用带有选择器的背景。这是演示代码

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true">
        <shape android:shape="rectangle">
            <solid android:color="@color/yourEnabledColor" />
        </shape>
    </item>
    <item android:state_enabled="false">
        <shape android:shape="rectangle">
            <solid android:color="@color/yourDisabledColor" />
        </shape>
    </item>
</selector>

原文由 Awais Ahmad 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题