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

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


当前回答

你可以使用DrawableCompat。

public static Drawable setTint(Drawable drawable, int color) {
    final Drawable newDrawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTint(newDrawable, color);
    return newDrawable;
}

其他回答

我也遇到过类似的问题。我希望为一个基于颜色(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>

希望这能有所帮助。

对于ImageButton,您可以使用:

favoriteImageButton.setColorFilter(Color.argb(255, 255, 255, 255)); // White Tint

你可以使用DrawableCompat。

public static Drawable setTint(Drawable drawable, int color) {
    final Drawable newDrawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTint(newDrawable, color);
    return newDrawable;
}

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

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

你可以用

button.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.blue_100)));

但是我建议你使用昨天刚刚发布的支持库drawable tinting:

Drawable drawable = ...;

// Wrap the drawable so that future tinting calls work
// on pre-v21 devices. Always use the returned drawable.
drawable = DrawableCompat.wrap(drawable);

// We can now set a tint
DrawableCompat.setTint(drawable, Color.RED);
// ...or a tint list
DrawableCompat.setTintList(drawable, myColorStateList);
// ...and a different tint mode
DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_OVER);

你可以在这篇博客文章中找到更多信息(参见“可绘制着色”部分)。