动态改变高度的ViewPager

发布于 2021-09-11  93 次阅读


class CustomViewPager2: ViewPager {
    private var current = 0
    private var mheight = 0
    private val mChildrenViews: HashMap<Int, View> = LinkedHashMap<Int, View>()

    constructor(context: Context):super((context))
    constructor(context: Context,attributeSet: AttributeSet):super(context,attributeSet)

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (mChildrenViews.size > current) {
            val child = mChildrenViews[current]
            child!!.measure(widthMeasureSpec,MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
            mheight = child.measuredHeight
        }
        super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(mheight,MeasureSpec.EXACTLY))
    }

    fun resetHeight(position: Int){
        current = position
        if (mChildrenViews.size > current) {
            var layoutParams = layoutParams
            if (layoutParams == null) {
                layoutParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, mheight)
            } else {
                layoutParams.height = mheight
            }
            setLayoutParams(layoutParams)
        }
    }

    fun setObjectForPosition(view: View, position: Int) {
        mChildrenViews[position] = view
    }
}
届ける言葉を今は育ててる
最后更新于 2021-09-11