有一个需求:
列表高度随内容条数增多而增高,当达到一定高度值时,则不再增高
如何实现呢?
我们知道RecyclerView有android:minHeight
属性用来设置最小高度,然而设置最大高度却没有android:maxHeight
???
那我们自己造一个!
class MaxHeightRecycler(context: Context, attrs: AttributeSet?) : RecyclerView(context, attrs) {
private var maxHeight: Float
init {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecycler)
maxHeight = typedArray.getDimension(R.styleable.MaxHeightRecycler_maxHeight, 200.dp)
typedArray.recycle()
}
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
val maxHeightSpec = MeasureSpec.makeMeasureSpec(maxHeight.toInt(), MeasureSpec.AT_MOST)
super.onMeasure(widthSpec, maxHeightSpec)
}
}
attrs.xml
<declare-styleable name="MaxHeightRecycler">
<attr name="maxHeight" format="dimension" />
</declare-styleable>
Kotlin扩展函数 200.dp
val Float.dp
get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, Resources.getSystem().displayMetrics)
val Int.dp
get() = this.toFloat().dp
Finish~