package com.gh.gamecenter.common.view

import android.content.Context
import android.util.AttributeSet
import androidx.core.widget.NestedScrollView
import com.gh.gamecenter.common.R


class MaxHeightNestedScrollView(context: Context, attrs: AttributeSet? = null) : NestedScrollView(context, attrs) {

    var maxHeight = 0F
    var scrollChangedListener: ScrollScrollChangedListener? = null

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightNestedScrollView)
        maxHeight = typedArray.getDimension(R.styleable.MaxHeightNestedScrollView_mMaxHeight, 0f)
        typedArray.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var newHeightMeasureSpec = 0
        try {
            newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight.toInt(), MeasureSpec.AT_MOST)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        //重新计算控件高、宽
        super.onMeasure(widthMeasureSpec, newHeightMeasureSpec)
    }

    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        super.onScrollChanged(l, t, oldl, oldt)
        scrollChangedListener?.onScrollChanged(l, t, oldl, oldt)
    }

    interface ScrollScrollChangedListener {
        fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int)
    }
}