How to add button tint programmatically

前端 未结 15 930
时光取名叫无心
时光取名叫无心 2020-11-30 23:38

In the new AppCompat library, we can tint the button this way:

15条回答
  •  既然无缘
    2020-12-01 00:38

    If you are using Kotlin and Material Design, you can change color of your MaterialButton like this:

    myButton.background.setTintList(ContextCompat.getColorStateList(context, R.color.myColor))
    

    You can improve it even better by creating an extension function for your MaterialButton in order to make you code more readable and your coding little more convenient:

    fun MaterialButton.changeColor(color: Int) {
        this.background.setTintList(ContextCompat.getColorStateList(context, color))
    }
    

    Then, you can use your function everywhere like this:

    myButton.changeColor(R.color.myColor)
    

提交回复
热议问题