Android:具有可变高度的 LinearLayout 返回高度 0

问题描述 投票:0回答:0

我有自定义

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
    }
}
android android-recyclerview android-linearlayout
© www.soinside.com 2019 - 2024. All rights reserved.