有一個需求:
列表高度隨內(nèi)容條數(shù)增多而增高崩哩,當(dāng)達到一定高度值時,則不再增高
如何實現(xiàn)呢旱物?
我們知道RecyclerView有android:minHeight
屬性用來設(shè)置最小高度,然而設(shè)置最大高度卻沒有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擴展函數(shù) 200.dp
val Float.dp
get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, Resources.getSystem().displayMetrics)
val Int.dp
get() = this.toFloat().dp
Finish~