前言
在平常的開發(fā)中應(yīng)該都遇到過在給RecyclerView加一個(gè)高度上限, 但是在當(dāng)前版本的lib中是不支持這個(gè)操作的哦.. 手動(dòng)動(dòng)態(tài)設(shè)定也不是很直觀, 用同級(jí)別view擠壓的方式可以實(shí)現(xiàn)效果,但是已經(jīng)背離了初衷, 將代碼放在下方, 目前我用著沒問題, 如果是v7包的把a(bǔ)ndroidx換成v7包即可. 體量比較小沒用上傳github ... 轉(zhuǎn)載請(qǐng)注明
未使用MaxHeight

未使用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中盡量不要上下依賴然后高度設(shè)定為0dp這種用法, 適用于各種LayoutManager , java項(xiàng)目一樣適用, 添加kt支持庫(kù)之后就行了, 或者翻譯成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>