ChipGroup 使用文档
1. 简介
ChipGroup 是 Material 组件中用于承载多个 Chip 的容器,适合以下场景:
- 标签展示(不可点击)
- 条件筛选(单选/多选)
- 动态标签列表(如识别结果、关键词等)
在当前项目中,ChipGroup 用于"识别结果标签列表"的展示,并配合 RecyclerView 实现"折叠/展开"效果。
2. 依赖要求
项目已包含依赖:
gradle
implementation 'com.google.android.material:material:1.9.0'
3. 基础 XML 用法
xml
<com.google.android.material.chip.ChipGroup
android:id="@+id/chip_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:singleLine="false"
app:chipSpacingHorizontal="6dp"
app:chipSpacingVertical="6dp" />
常用属性
app:singleLine:是否单行显示,false表示自动换行app:chipSpacingHorizontal:横向间距app:chipSpacingVertical:纵向间距app:singleSelection:是否单选模式app:selectionRequired:单选时是否要求必须有一个选中项
4. 动态添加 Chip(展示型)
适用于识别结果、标签云等动态数据场景。
kotlin
private fun renderChips(chipGroup: ChipGroup, tags: List<String>) {
chipGroup.removeAllViews()
val showTags = if (tags.isEmpty()) listOf("无") else tags
showTags.forEach { tag ->
val chip = Chip(chipGroup.context).apply {
text = "\u2022 $tag"
isClickable = false
isCheckable = false
closeIcon = null
chipStartPadding = 10f
chipEndPadding = 10f
setTextColor(0xFFBFC9EA.toInt())
textSize = 13f
setChipBackgroundColorResource(android.R.color.transparent)
setBackgroundResource(R.drawable.bg_tag_chip)
}
chipGroup.addView(chip)
}
}
注意事项
- RecyclerView item 复用时必须先调用
removeAllViews(),避免重复叠加。 - 展示型场景建议设置
isClickable=false、isCheckable=false。
5. 单选/多选筛选用法
如果用于筛选功能,可开启可选中状态:
xml
<com.google.android.material.chip.ChipGroup
android:id="@+id/chip_group_filter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:singleSelection="true"
app:selectionRequired="true" />
kotlin
val chip = Chip(context).apply {
id = View.generateViewId()
text = "前方"
isCheckable = true
}
chipGroup.addView(chip)
chipGroup.setOnCheckedStateChangeListener { _, checkedIds ->
// checkedIds: 当前选中的 Chip id 列表
}
6. 折叠/展开场景实现建议
当标签数量较多时,建议在 Adapter 中控制:
- 设置折叠阈值(如 3 个)
- 折叠态仅显示前 N 个标签
- 超过阈值显示箭头按钮
- 点击箭头切换
expanded状态并notifyItemChanged(position)
示例逻辑:
kotlin
val canExpand = item.tags.size > collapsedVisibleCount
val visibleTags = if (item.expanded || !canExpand) {
item.tags
} else {
item.tags.take(collapsedVisibleCount)
}
renderChips(binding.chipGroup, visibleTags)
7. 性能建议
- 避免在高频回调中无条件重建全部 Chip。
- 先比较新旧数据,只有变化时再刷新 item。
- 可结合节流(throttle)降低 UI 更新频率。
- 极大数据量时可考虑将标签改为文本聚合展示,降低 View 数量。