Android ChipGroup高度计算异常:wrap_content仅适配最后子View高度
Android Material ChipGroup wrap_content高度计算异常问题
问题现象
使用Material Components 1.12.0时,ChipGroup设置wrap_content高度会出现计算异常:仅以最后一个子View的高度作为自身高度,导致前面高度更高的子View被截断。
比如这段布局代码:
<?xml version="1.0" encoding="utf-8"?> <com.google.android.material.chip.ChipGroup xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#CEECF6"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Big text" android:textSize="24sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Small text" android:textSize="14sp" /> </com.google.android.material.chip.ChipGroup>
运行后ChipGroup高度只适配了小字体的TextView,大字体TextView会被截断;但把大字体TextView移到最后,高度就能正常适配最高子View。
问题原因
这是Material Components 1.12.0版本中ChipGroup的测量逻辑bug:在onMeasure方法计算高度时,错误地仅保留最后一个子View的测量高度,没有遍历所有子View取最大值。
解决办法
1. 降级依赖版本
暂时降级到1.11.0版本,该版本的ChipGroup测量逻辑正常,能正确计算wrap_content高度。修改build.gradle(或build.gradle.kts)中的依赖:
implementation 'com.google.android.material:material:1.11.0'
2. 自定义ChipGroup修复测量逻辑
继承ChipGroup并重写onMeasure,手动计算所有子View的最大高度:
class FixedChipGroup @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = com.google.android.material.R.attr.chipGroupStyle ) : ChipGroup(context, attrs, defStyleAttr) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) // 仅针对wrap_content模式修复 if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { var maxChildHeight = 0 for (i in 0 until childCount) { val child = getChildAt(i) maxChildHeight = max(maxChildHeight, child.measuredHeight) } // 加上自身的padding值 val finalHeight = maxChildHeight + paddingTop + paddingBottom setMeasuredDimension(measuredWidth, finalHeight) } } }
然后在布局中替换为自定义的FixedChipGroup:
<com.your.package.name.FixedChipGroup xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#CEECF6"> <!-- 子View保持不变 --> </com.your.package.name.FixedChipGroup>
3. 等待官方修复
可以关注Material Components的官方仓库,该bug大概率会在后续版本中修复,待修复后升级到最新版本即可。
内容的提问来源于stack exchange,提问作者Goltsev Eugene
相关产品推荐
相关产品推荐

