如何通过代码设置MaterialSwitch的thumbTint属性
代码实现MaterialSwitch的状态色切换(替代XML选择器)
你可以通过代码创建ColorStateList来模拟XML选择器的效果,然后将其设置给MaterialSwitch的thumbTint属性,具体实现如下:
1. 构建对应状态的ColorStateList
直接在代码中定义选中、未选中状态对应的颜色,和原XML选择器逻辑完全一致:
// Kotlin 实现 val colorStateList = ColorStateList( arrayOf( intArrayOf(android.R.attr.state_checked), // 选中状态 intArrayOf(-android.R.attr.state_checked) // 未选中状态 ), intArrayOf( ContextCompat.getColor(this, R.color.colorPrimary), // 选中时的颜色 ContextCompat.getColor(this, R.color.colorSwitch) // 未选中时的颜色 ) )
// Java 实现 int[][] states = new int[][] { new int[] { android.R.attr.state_checked }, // 选中状态 new int[] { -android.R.attr.state_checked } // 未选中状态 }; int[] colors = new int[] { ContextCompat.getColor(this, R.color.colorPrimary), // 选中时的颜色 ContextCompat.getColor(this, R.color.colorSwitch) // 未选中时的颜色 }; ColorStateList colorStateList = new ColorStateList(states, colors);
2. 绑定到MaterialSwitch
找到布局中的MaterialSwitch实例,将创建好的ColorStateList赋值给它的thumbTintList:
// Kotlin val switchView = findViewById<MaterialSwitch>(R.id.sw_update_list) switchView.thumbTintList = colorStateList
// Java MaterialSwitch switchView = findViewById(R.id.sw_update_list); switchView.setThumbTintList(colorStateList);
适配多主题切换场景
如果你的应用支持多主题切换,要确保颜色是当前主题下的对应值,可以通过主题属性获取动态颜色,替代固定资源引用:
// Kotlin 从主题中获取colorPrimary val typedValue = TypedValue() theme.resolveAttribute(android.R.attr.colorPrimary, typedValue, true) val colorPrimary = ContextCompat.getColor(this, typedValue.resourceId)
// Java 从主题中获取colorPrimary TypedValue typedValue = new TypedValue(); getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true); int colorPrimary = ContextCompat.getColor(this, typedValue.resourceId);
主题切换后重新执行上述代码,即可更新MaterialSwitch的thumb颜色。
内容的提问来源于stack exchange,提问作者Marvin Stelter
相关产品推荐
相关产品推荐

