Button.setEnabled(false) 不会使按钮变灰

Button.setEnabled(false) does not make the button grey

我的申请中有一个 Button。当我在上面使用 setEnabled(false) 时,它会变成灰色。但是,如果我先修改 Button 的背景,然后在其上调用 setEnabled(false),它不会变灰(但 Button 未启用)。为什么会这样,我怎样才能让它变灰呢?

针对您的问题有几个决定: 最简单的:改变按钮的背景。 或者您可以使用选择器:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:color="#9e9e9e"
        />
    <item
        android:state_enabled="true"
        android:color="#56934d"
        />
</selector>

在我看来,最简单的解决方案是在 activity 中设置按钮的背景。像下面这样:

button.setAlpha(.5f);
button.setClickable(false);

.5f alpha 相当于灰色禁用按钮。如果按钮的背景是图片,这通常很有用。

Why is that

通常,Button 的背景是 ColorStateList:特定的颜色被分配给不同的状态,如 "enabled" 或 "disabled"(可能的状态取决于类型小部件)。如果状态发生变化,运行时会相应地更改背景颜色。

您提供了一种颜色作为 Button 的背景,因此无论 Button 的当前状态如何,它都会被使用。

and how can I make it grey whatever happens to it?

创建一个包含 ColorStateList 的可绘制资源(例如以下 guide)并将其用作背景可绘制资源。