前言
在平常的开发中应该都遇到过在给RecyclerView加一个高度上限, 但是在当前版本的lib中是不支持这个操作的哦.. 手动动态设定也不是很直观, 用同级别view挤压的方式可以实现效果,但是已经背离了初衷, 将代码放在下方, 目前我用着没问题, 如果是v7包的把androidx换成v7包即可. 体量比较小没用上传github ... 转载请注明
未使用MaxHeight
需求
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.min
/**
* email: ningning21_h@foxmail.com
*/
class MaxHeightRecyclerView : RecyclerView {
private var maxHeight: Int = -1
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
attrs?.let { attrSet ->
val attrRes = intArrayOf(android.R.attr.maxHeight)
val types = context.obtainStyledAttributes(attrSet, attrRes)
maxHeight = types.getDimensionPixelSize(0, -1)
types.recycle()
}
}
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
val hSize = MeasureSpec.getSize(heightSpec)
val heightMeasureSpec = if (maxHeight < 0) {
heightSpec
} else {
when (MeasureSpec.getMode(heightSpec)) {
MeasureSpec.AT_MOST -> MeasureSpec.makeMeasureSpec(min(hSize, maxHeight), MeasureSpec.AT_MOST)
MeasureSpec.UNSPECIFIED -> MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST)
MeasureSpec.EXACTLY -> MeasureSpec.makeMeasureSpec(min(hSize, maxHeight), MeasureSpec.EXACTLY)
else -> MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST)
}
}
super.onMeasure(widthSpec, heightMeasureSpec)
}
}
用法
代码中android:layout_height属性最好用wrap_content , 在constraintlayout中尽量不要上下依赖然后高度设定为0dp这种用法, 适用于各种LayoutManager , java项目一样适用, 添加kt支持库之后就行了, 或者翻译成java吧
注: android:maxHeight只能在constraintlayout中使用
<MaxHeightRecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxHeight="@dimen/comm_dp_84"
android:layout_marginBottom="@dimen/dp_4"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@id/tag"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="@layout/item">
</MaxHeightRecyclerView>