如何通过代码设置Android Chip选中状态的背景颜色?
问题修复方案
问题根源
- 代码中使用
ColorStateList.valueOf()设置单一固定颜色,直接覆盖了XML中定义的状态颜色列表,导致Chip状态切换时无法触发颜色变化 - XML文件中选中状态误用
state_selected,而isCheckable=true的Chip,其选中状态对应的是state_checked,而非state_selected
1. 修正Chip背景颜色XML文件
将状态统一为state_checked,并调整顺序(状态匹配优先级从上到下,默认状态放在最后):
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 选中状态颜色 --> <item android:color="@color/corporate_blue2" android:state_checked="true"/> <!-- 未选中状态颜色 --> <item android:color="@color/corporate_green" android:state_checked="false"/> <!-- 默认 fallback 颜色 --> <item android:color="@color/corporate_green"/> </selector>
将该文件放在res/color目录下,命名为chip_background_selector.xml
2. 修正Fragment中的Chip创建代码
移除单一颜色的设置,改为加载XML定义的状态颜色列表:
private fun createChip(label: String, time: String, id: Int): Chip { val chip = Chip(context, null, R.style.CustomChipStyle) // 加载XML中的状态颜色列表 chip.chipBackgroundColor = ContextCompat.getColorStateList(requireContext(), R.color.chip_background_selector) chip.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) chip.text = label chip.isCheckable = true // isCheckable=true 已自动开启点击交互,无需重复设置isClickable chip.setOnClickListener { binding.lytSelectTime.removeAllViews() val scrollView = HorizontalScrollView(context) val chipGroup = ChipGroup(context) chipGroup.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) // 补充后续逻辑代码 } return chip }
内容的提问来源于stack exchange,提问作者Mehmet Hikmet
相关产品推荐
相关产品推荐

