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

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


当前回答

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

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

其他回答

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

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))

通过提供一个真实的代码情况来适当地扩展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);

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

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

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

对于ImageButton,您可以使用:

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

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

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