在新的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"
/>
如何在我的代码中以编程方式设置按钮的色调?
我基本上是试图实现基于一些用户输入的按钮的条件着色。
如果你正在使用Kotlin和Material Design,你可以像这样改变MaterialButton的颜色:
myButton.background.setTintList(ContextCompat.getColorStateList(context, R.color.myColor))
你可以通过为你的MaterialButton创建一个扩展函数来更好地改进它,以使你的代码更易于阅读,你的编码更方便:
fun MaterialButton.changeColor(color: Int) {
this.background.setTintList(ContextCompat.getColorStateList(context, color))
}
然后,你可以像这样在任何地方使用你的函数:
myButton.changeColor(R.color.myColor)