1. 程式人生 > 其它 >【CustomView】封裝Spinner(可設定高度)- LimitPopupHeightSpinner

【CustomView】封裝Spinner(可設定高度)- LimitPopupHeightSpinner

技術標籤:# Custom-viewandroidSpinnerLimitHeight

### 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()
        }
    }
}