首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用AppCompat设置按钮的禁用颜色?

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

Stack Overflow用户
提问于 2016-03-05 13:49:37
回答 6查看 48.9K关注 0票数 41

我使用此样式来更改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)时,它保持相同的颜色。我该如何处理此案例?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2016-03-05 14:58:01

您没有正确使用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"/>

this answer on using the Widget.AppCompat.Button.Colored style中所述,禁用的颜色由colorButtonNormal控制,启用的颜色由colorAccent控制。通过使用ThemeOverlay.AppCompat.DarktextColor会自动更改为深色,这意味着您可能根本不需要自定义ThemeOverlay

票数 87
EN

Stack Overflow用户

发布于 2016-03-05 14:02:54

您应该使用带有选择器的背景,而不是对按钮使用颜色。以下是演示代码

<?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>
票数 16
EN

Stack Overflow用户

发布于 2016-05-18 20:15:40

将接受的解决方案与自定义小部件相结合,我们可以通过设置alpha来显示禁用的按钮。这应该适用于任何按钮和文本颜色组合:

public class ButtonWidget extends AppCompatButton {

    public ButtonWidget(Context context) {
        super(context);
    }

    public ButtonWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ButtonWidget(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setEnabled(boolean enabled) {
        setAlpha(enabled ? 1 : 0.5f);
        super.setEnabled(enabled);
    }

}
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35810614

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档