方法一,自定义view继承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>
//在xml中使用自定义的Recyclerview
app:maxHeight = "300dp"
方法二:
根据list的条目来决定显示
val lp: ViewGroup.LayoutParams = mRecyclerView!!.layoutParams
if (list.size!! > 5) {//当列表条目大于5时 设置为固定的高度
lp.height = DensityUtil.dip2px(300.0f);
}
mRecyclerView!!.layoutParams = lp