在新的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"
    />

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


当前回答

我也遇到过类似的问题。我希望为一个基于颜色(int)值的视图着色一个复杂的可绘制背景。 我成功地使用了代码:

ColorStateList csl = new ColorStateList(new int[][]{{}}, new int[]{color});
textView.setBackgroundTintList(csl);

其中color是一个int值,表示所需的颜色。 这表示简单的xml ColorStateList:

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:color="color here"/>
</selector>

希望这能有所帮助。

其他回答

这很容易在材质设计库的新材质按钮中处理,首先,添加依赖项:

implementation 'com.google.android.material:material:1.1.0-alpha07'

然后在你的XML中,使用这个按钮:

<com.google.android.material.button.MaterialButton
    android:id="@+id/accept"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/i_accept"
    android:textSize="18sp"
    app:backgroundTint="@color/grayBackground_500" />

当你想改变颜色时,这是Kotlin中的代码,它没有被弃用,可以在Android 21之前使用:

accept.backgroundTintList = ColorStateList.valueOf(ResourcesCompat.getColor(resources, 
R.color.colorPrimary, theme))

你可以这样使用:

myButton.backgroundTintList = AppCompatResources.getColorStateList(context, R.color.primary_variant)

如果你正在使用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,你可以使用这段代码,基本上任何视图。为我工作。

val states = arrayOf(intArrayOf(android.R.attr.state_enabled))
                    val colors = intArrayOf(Color.GREEN) // your color here
                    val colorStateList = ColorStateList(states, colors)
                  ViewCompat.setBackgroundTintList(yourButtonHere,colorStateList)

Kotlin版本,祝阅读这篇文章的每个人都有美好的一天;)

顺便说一句。如果你创建了一些可绘制的背景形状,这应该只覆盖色调颜色。


简单的方法

在Java中

myButton.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.white)));

在Kotlin

myButton.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.white)))