How to change the track color of a SwitchCompat

后端 未结 10 1842
孤城傲影
孤城傲影 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:25

    Below is the AppCompat way of changing both the track and thumb color programmatically, for a specific SwitchCompat. For this example, I have hardcoded the thumbColor to red. Ideally, you would set the color through a second method parameter.

    Please note that when the switch is checked, a ripple is displayed. The ripple color will not be changed by the code below.

    public static void setSwitchColor(SwitchCompat v) {
        // thumb color of your choice
        int thumbColor = Color.RED;
    
        // trackColor is the thumbColor with 30% transparency (77)
        int trackColor = Color.argb(77, Color.red(thumbColor), Color.green(thumbColor), Color.blue(thumbColor));
    
        // setting the thumb color
        DrawableCompat.setTintList(v.getThumbDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        thumbColor,
                        Color.WHITE
                }));
    
        // setting the track color
        DrawableCompat.setTintList(v.getTrackDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        trackColor,
                        Color.parseColor("#4D000000") // full black with 30% transparency (4D)
                }));
    }
    

提交回复
热议问题