在新的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);

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

其他回答

你试过这样的东西吗?

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

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

你可以这样使用:

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

我设法让我的工作的方式是使用CompoundButtonCompat。setButtonTintList(按钮、色彩)。

据我所知,无论android版本如何,这都是可行的。

使用setBackgroundTintList有三个选项

int myColor = Color.BLACK;

按钮。setBackgroundTintList(new ColorStateList(EMPTY, new int[] {myColor})); button.setBackgroundTintList (ColorStateList.valueOf (myColor)); button.setBackgroundTintList (contextInstance.getResources () .getColorStateList (R.color.my_color));

如果你不想关心不同版本的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版本,祝阅读这篇文章的每个人都有美好的一天;)

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