Android 5 上的 AppCompatButton:app:backgroundTint 有效但不支持 BackgroundTintList :(

AppCompatButton on Android 5: app:backgroundTint works but supportBackgroundTintList does NOT :(

我需要重用 XML 布局并以编程方式更改按钮颜色。 在 Android 5 中,在 XML 中应用 app:backgroundTint 更改按钮颜色,但我需要以编程方式进行,我这样做了 in Recyclerview:

holder.button.supportBackgroundTintList = ContextCompat.getColorStateList(context, backgroundColorRes)

这没有效果。

setSupportBackgroundTintList() 方法用 @RestrictTo({Scope.LIBRARY_GROUP}) 注释,这意味着您不应该直接调用它。相反,您应该使用 ViewCompat.setBackgroundTintList().

尝试将您的代码更改为:

val colorStateList = ContextCompat.getColorStateList(context, backgroundColorRes)
ViewCompat.setBackgroundTintList(holder.button, colorStateList)

如果您查看 ViewCompat.setBackgroundTintList() 的源代码,您会发现它对 API 21+(Android 5 及更高版本)的处理方式与早期版本不同。 "support" 背景色很有可能只适用于 Android 的早期版本,而 ViewCompat 会做到这一点,因此您不必考虑它。