參考:https://stackoverflow.com/questions/49449828/maxheight-does-not-work-on-recyclerview
way1: 通過(guò)約束布局灭抑,設(shè)置高度默認(rèn)為wrap-content,最大高度為特定值继控。
要求: 約束布局,需要升級(jí)到2以上
核心代碼:
gradle文件定義:
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta6'
xml中設(shè)置RecyclerView
android:layout_height="0dp"
app:layout_constraintHeight_default="wrap"
app:layout_constraintHeight_max="280dp"
way2:自定義view. 在onMeasure中設(shè)置最大高度
/**
* 設(shè)置 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)
}
}