RecyclerView设置最大高度

有一个需求:

列表高度随内容条数增多而增高,当达到一定高度值时,则不再增高

如何实现呢?

我们知道RecyclerView有android:minHeight属性用来设置最小高度,然而设置最大高度却没有android:maxHeight???

那我们自己造一个!

class MaxHeightRecycler(context: Context, attrs: AttributeSet?) : RecyclerView(context, attrs) {

    private var maxHeight: Float

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecycler)
        maxHeight = typedArray.getDimension(R.styleable.MaxHeightRecycler_maxHeight, 200.dp)
        typedArray.recycle()
    }

    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
        val maxHeightSpec = MeasureSpec.makeMeasureSpec(maxHeight.toInt(), MeasureSpec.AT_MOST)
        super.onMeasure(widthSpec, maxHeightSpec)
    }
}

attrs.xml

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

Kotlin扩展函数 200.dp

val Float.dp
    get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, Resources.getSystem().displayMetrics)
val Int.dp
    get() = this.toFloat().dp

Finish~

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容