在新的AppCompat库中,我们可以这样为按钮着色:

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/follow"
    android:id="@+id/button_follow"
    android:backgroundTint="@color/blue_100"
    />

如何在我的代码中以编程方式设置按钮的色调? 我基本上是试图实现基于一些用户输入的按钮的条件着色。


当前回答

通过提供一个真实的代码情况来适当地扩展dimsuz的回答,请参阅下面的代码片段:

    Drawable buttonDrawable = button.getBackground();
    buttonDrawable = DrawableCompat.wrap(buttonDrawable);
    //the color is a direct color int and not a color resource
    DrawableCompat.setTint(buttonDrawable, Color.RED);
    button.setBackground(buttonDrawable);

此解决方案适用于使用可绘制对象作为按钮背景的场景。它也适用于前棒棒糖时代的设备。

其他回答

芬兰湾的科特林,

checkbox.buttonTintList = AppCompatResources.getColorStateList(context, color.colorPrimary)

如果你正在使用Kotlin和Material Design,你可以像这样改变MaterialButton的颜色:

myButton.background.setTintList(ContextCompat.getColorStateList(context, R.color.myColor))

你可以通过为你的MaterialButton创建一个扩展函数来更好地改进它,以使你的代码更易于阅读,你的编码更方便:

fun MaterialButton.changeColor(color: Int) {
    this.background.setTintList(ContextCompat.getColorStateList(context, color))
}

然后,你可以像这样在任何地方使用你的函数:

myButton.changeColor(R.color.myColor)

根据文档,android的相关方法:backgroundTint是setBackgroundTintList(ColorStateList list)

更新

按照此链接了解如何创建颜色状态列表资源。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:color="#your_color_here" />
</selector>

然后使用

setBackgroundTintList(contextInstance.getResources().getColorStateList(R.color.your_xml_name));

哪里contextInstance是一个Context的实例


使用AppCompart

btnTag.setSupportButtonTintList(ContextCompat.getColorStateList(Activity.this, R.color.colorPrimary));

你试过这样的东西吗?

button.setBackgroundTintList(getResources().getColorStateList(R.id.blue_100));

注意getResources()将只在活动中工作。但它也可以在任何上下文中调用。

似乎视图有自己的色调管理机制,所以最好将色调列表:

ViewCompat.setBackgroundTintList(
    editText, 
    ColorStateList.valueOf(errorColor));