How to change the track color of a SwitchCompat

后端 未结 10 1841
孤城傲影
孤城傲影 2020-11-29 18:01

I\'ve tried using the following link to change the color of a SwitchCompat:

How to change the color of a SwitchCompat

Notice the low constrast in my switch:<

10条回答
  •  迷失自我
    2020-11-29 18:11

    I was having the same problem. Finally solved it programatically with this Kotlin code

    fun tintSwitchButton(sw: SwitchCompat, resolvedColor: Int) {
        val states = arrayOf(
                intArrayOf(-android.R.attr.state_pressed),
                intArrayOf(android.R.attr.state_pressed)
        )
    
        DrawableCompat.setTintList(sw?.trackDrawable, ColorStateList(
                states,
                intArrayOf(resolvedColor, resolvedColor)
        ))
    
        DrawableCompat.setTintList(sw?.thumbDrawable, ColorStateList(
                states,
                intArrayOf(Color.WHITE, Color.WHITE)
        ))
    }
    

    And the function call is

    tintSwitchButton(switchCompat, Color.rgb(214, 0, 0))
    

    You can also create an extension function:

    fun SwitchCompat.tint(resolvedColor: Int) {
        val states = arrayOf(
            intArrayOf(-android.R.attr.state_pressed),
            intArrayOf(android.R.attr.state_pressed)
        )
    
        DrawableCompat.setTintList(trackDrawable, ColorStateList(
            states,
            intArrayOf(resolvedColor, resolvedColor)
        ))
    
        DrawableCompat.setTintList(thumbDrawable, ColorStateList(
            states,
            intArrayOf(Color.WHITE, Color.WHITE)
        ))
    }
    

    So the call would be easier

    switchCompat.tint(Color.rgb(214,0,0))
    

提交回复
热议问题