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

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


当前回答


简单的方法

在Java中

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

在Kotlin

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

其他回答

简单的我们也可以用于imageview

    imageView.setColorFilter(ContextCompat.getColor(context,
R.color.COLOR_YOUR_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
checkbox.ButtonTintList = ColorStateList.ValueOf(Android.Color.White);

使用ButtonTintList代替BackgroundTintList

你可以这样使用:

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

颜色可以添加到按钮如下:

filterBtn.setBackgroundTintList(ContextCompat.getColorStateList(context,R.color.colorPrimary))