我有自定义
LinearLayout
,可以根据它所包含的内容将高度设置为最大或最小。但是如果这个LinearLayout
里面有RecyclerView,当我调用adapter.notifyDataSetChange()
以刷新RecyclerView
内容时,onMeasure仍然返回0。
RecyclerView
中有大约 300 个项目,但是 onMeasure
的父母的RecyclerView
仍然测量 0 高度。我需要将 RecyclerView
的高度限制为在视图初始化时设置的特定值。
自定义线性布局
class LinearLayoutWithVariableHeight: LinearLayout {
companion object {
var WITHOUT_HEIGHT_VALUE = -1
}
private var maxHeight = WITHOUT_HEIGHT_VALUE
private var minHeight = WITHOUT_HEIGHT_VALUE
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var measuredHeight = heightMeasureSpec
val currHeight = getCurrContentHeight()
try {
val heightSize: Int
App.log("LinearLayoutWithMaxHeight: onMeasure curr_height: $currHeight, max: $maxHeight")
if (maxHeight != WITHOUT_HEIGHT_VALUE && currHeight > maxHeight) {
App.log("LinearLayoutWithMaxHeight: onMeasure set xy max height")
heightSize = maxHeight
} else if (minHeight != WITHOUT_HEIGHT_VALUE && currHeight < minHeight){
App.log("LinearLayoutWithMaxHeight: onMeasure set xy min height")
heightSize = min(minHeight, maxHeight)
} else {
heightSize = currHeight
}
App.log("LinearLayoutWithMaxHeight: onMeasure heightSize: $heightSize")
measuredHeight = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.AT_MOST)
layoutParams.height = heightSize
} catch (e: Exception) {
} finally {
App.log("LinearLayoutWithMaxHeight: onMeasure final: $measuredHeight")
super.onMeasure(widthMeasureSpec, measuredHeight)
}
}
private fun getCurrContentHeight(): Int{
var height = 0
for (i in 0 until childCount) {
val child = getChildAt(i)
val h = child.measuredHeight
App.log("LinearLayoutWithMaxHeight: getCurrChildHeight: $h")
if (h > height) height = h
}
return height
}
fun setMaxHeight(maxHeight: Int) {
this.maxHeight = maxHeight
}
fun setMinHeight(minHeight: Int) {
this.minHeight = minHeight
}
}