安卓按钮背景颜色

87

我想在我的应用程序中设置按钮的背景颜色,但是我无法达到我想要的结果...

我要设置的颜色是holo_green_light(#ff99cc00)。为了做到这一点,我使用 setColorFilter(0xff99cc00, PorterDuff.Mode.MULTIPLY);

我得到的颜色不是holo_green_light,而是混合了浅灰色和holo_green_light

我尝试使用LightingColorFilter没有取得太大的成功。

有没有一种编程的方法,使得按钮看起来像一个按钮,而不是一个带有所需颜色的平面矩形。


尝试使用android:background="@drawable/button"。 - Giant
14个回答

0
除了Mark Proctor的回答之外:
如果您想保留默认样式,但在按钮上进行条件着色,只需设置backgroundTint属性,如下所示:
android:backgroundTint="@drawable/styles_mybutton"

创建关联文件/res/drawable/styles_mybutton.xml,然后使用以下模板并根据您的口味更改颜色:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Disabled state-->
    <item android:state_enabled="false"
        android:color="@android:color/white">
    </item>
    <!-- Default state-->
    <item
        android:color="#cfc">
    </item>
</selector>

0

随着1.2.0-alpha06版本的Material Design库,现在我们可以在MaterialButton组件上使用android:background="..."

<com.google.android.material.button.MaterialButton
    android:background="#fff"
    ...
/>

您可以使用 android:background 属性来设置可绘制对象。如果您只想更改颜色,则可以使用 app:backgroundTint 属性。 - Gabriele Mariotti
1
要能够在MaterialButton中使用背景(例如使用drawable),您还需要将app:background tint设置为nullapp:backgroundTint =“@ null” android:background =“@ drawable / bg_drawable” - Max Cruz

0

我在使用Android Studio Flamingo默认设置时遇到了同样的问题。但发现需要将主题更改为AppCompat.NoAction或类似的主题,以便您的设计视图中可以看到颜色。在Android Studio的Designer视图顶部还有一个主题选择器选项,可供选择主题选项。

之后,您应该能够在按钮样式中看到变化。您可以使用自定义drawable,如android:background="@drawble/some_asset"android:backgroundTint="some_hex_color"

希望这能解决问题。


0
以编程方式实现:
val pressedColor = ColorDrawable(Color.LTGRAY)
val states = arrayOf(
    intArrayOf(android.R.attr.state_pressed),
    intArrayOf(android.R.attr.state_focused),
    intArrayOf()
)
val drawables = arrayOf(
    pressedColor,
    pressedColor,
    ColorDrawable(Color.TRANSPARENT)
)
val stateListDrawable = StateListDrawable()

for (i in states.indices) {
    stateListDrawable.addState(states[i], drawables[i])
}

button.background = stateListDrawable

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接