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

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


当前回答

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

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

其他回答

使用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));

除了Shayne3000的答案,你还可以使用颜色资源(不仅仅是int颜色)。芬兰湾的科特林版:

var indicatorViewDrawable = itemHolder.indicatorView.background
indicatorViewDrawable = DrawableCompat.wrap(indicatorViewDrawable)
val color = ResourcesCompat.getColor(context.resources, R.color.AppGreenColor, null) // get your color from resources
DrawableCompat.setTint(indicatorViewDrawable, color)
itemHolder.indicatorView.background = indicatorViewDrawable

你试过这样的东西吗?

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

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

下面是如何在kotlin中做到这一点:

view.background.setTint(ContextCompat.getColor(context, textColor))

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

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