RecyclerView 设置最大高度

参考:https://stackoverflow.com/questions/49449828/maxheight-does-not-work-on-recyclerview

way1: 通过约束布局,设置高度默认为wrap-content,最大高度为特定值。

要求: 约束布局,需要升级到2以上
核心代码:
gradle文件定义:

implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta6'

xml中设置RecyclerView

android:layout_height="0dp"
app:layout_constraintHeight_default="wrap"
app:layout_constraintHeight_max="280dp"

way2:自定义view. 在onMeasure中设置最大高度

/**
 * 设置 recyclerView 最大高度
 */
class MaxHeightRecyclerView @JvmOverloads constructor(
        context: Context,
        attributeSet: AttributeSet? = null,
        defStyleAttr: Int = 0
) : RecyclerView(context, attributeSet, defStyleAttr) {

    companion object {
        const val TAG = "MaxHeightRecyclerView"
    }

    var MAX_HEIGHT: Float

    init {
        val typeArray = context.obtainStyledAttributes(attributeSet, R.styleable.MaxHeightRecyclerView)
        MAX_HEIGHT = typeArray.getDimension(R.styleable.MaxHeightRecyclerView_recyclerViewMaxHeight, 200f)
        LogUtils.d(TAG, "MAX_HEIGHT=$MAX_HEIGHT")

        typeArray.recycle()
    }

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

你可能感兴趣的:(RecyclerView 设置最大高度)