ok,这个就是重点了。
因为只是view本身高度的变化,我们只需要重写onMeasure
去计算高度即可。
来看onMeasure
:
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
//重置高度
allChildHeight = 0
firstChildHeight = 0
if (childCount > 0) {
//遍历计算高度
for (index in 0 until childCount) {
//这个地方实际使用中除了measuredHeight,以及margin等,也要计算在内
if (index == 0) {
firstChildHeight = getChildAt(index).measuredHeight
+getChildAt(index).marginTop + getChildAt(index).marginBottom
+this.paddingTop + this.paddingBottom
}
//实际使用时或包括padding等
allChildHeight += getChildAt(index).measuredHeight + getChildAt(index).marginTop + getChildAt(index).marginBottom
//最后一条的时候 加上当前view自身的padding
if (index == childCount - 1) {
allChildHeight += this.paddingTop + this.paddingBottom
}
}
// 根据是否展开设置高度
if (isOpen) {
setMeasuredDimension(
widthMeasureSpec,
firstChildHeight + ((allChildHeight - firstChildHeight) * animPercent).toInt()
)
} else {
setMeasuredDimension(
widthMeasureSpec,
allChildHeight - ((allChildHeight - firstChildHeight) * animPercent).toInt()
)
}
}
}
onMeasure
里面也是分了两个步骤的:
- 遍历计算高度
//遍历计算高度
for (i