### Spinner如果不限制高度,会出现这样的充满全屏的高度,这也是UI设计师不允许的
如下图所示:
这里需要判断列表数据的数量是否超出限制:
// set a limit sliding height
(limitPopupHeightSpinner).setSpinnerItem(data.size)
### 完整的代码:
@SuppressLint("AppCompatCustomView")
class LimitPopupHeightSpinner : Spinner {
constructor(context: Context, attrs: AttributeSet? = null) : super(context, attrs)
companion object {
private const val LIMIT_VISIBLE_SCROLL: Int = 4
}
private var spinnerItem: Int = 0
fun setSpinnerItem(spinnerItem: Int) {
this.spinnerItem = spinnerItem
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
super.onLayout(changed, l, t, r, b)
if (spinnerItem > LIMIT_VISIBLE_SCROLL) limitListPopupHeight()
}
private fun limitListPopupHeight() {
try {
val spinnerClass = android.widget.Spinner::class.java
val listPopup = spinnerClass
.getDeclaredField("mPopup")
.apply { isAccessible = true }
.get(this)
// Set popupWindow height
(listPopup as? ListPopupWindow)?.height = resources.getDimension(R.dimen.dp_314).toInt()
} catch (e: Exception) {
e.printStackTrace()
}
}
}