实用技巧 | RecyclerView 设置最大高度


class MaxRecyclerView : RecyclerView {
    
    
    private var mMaxHeight = 0

    constructor(context: Context) : super(context) {
    
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    
    
        init(context, attrs)
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    
    
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
    
    
        val arr = context.obtainStyledAttributes(attrs, R.styleable.MaxRecyclerView)
        mMaxHeight = arr.getLayoutDimension(R.styleable.MaxRecyclerView_maxHeight, mMaxHeight)
        arr.recycle()
    }

    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
    
    
        super.onMeasure(widthSpec, heightSpec)
        val height = measuredHeight
        if (height > mMaxHeight) {
    
    
            setMeasuredDimension(widthSpec, mMaxHeight)
        }
    }
}

如果测量的高度 大于 最大高度,则使用最大高度,否则默认使用测量的高度

    <declare-styleable name="MaxRecyclerView">
        <attr name="maxHeight" format="dimension" />
    </declare-styleable>

猜你喜欢

转载自blog.csdn.net/baidu_40389775/article/details/107566050
今日推荐