之前記錄過TextInputLayout這篇,除了有打字時,hint文字可以跑到EditText上方的功能,還有幾個小功能,今天就來記錄這兩個小功能 ↓
- EditText下方顯示輔助字眼提示
- EditText下方右方出現字數限制提示
xml寫法如下,各設定含意寫在註解
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<com.google.android.material.textfield.TextInputLayout | |
... | |
app:counterEnabled="true" | |
app:counterMaxLength="5" | |
app:errorEnabled="true" | |
app:helperText="@string/help_text" | |
app:helperTextEnabled="true" | |
...> | |
<!-- counterEnabled 字數限制是否開啟--> | |
<!-- counterMaxLength 字數所限制的長度--> | |
<!-- helperTextEnabled 下方提示字眼是否開啟--> | |
<!-- helperText 下方提示字眼--> | |
<!-- errorEnable 下方錯誤題示字眼是否開啟--> |
當這樣設定完後,可以發現下方提示與字數限制提示有正常顯示,但當超過字數時,下方提示字眼要怎麼換成錯誤題示字眼呢?
這邊就需要在程式端設定TextInputLayout,在TextInputEditText加上afterTextChanged Listener,當字數超過5或小於5就進行TextInputLayout的error設定,如下
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
textInputEditText.doAfterTextChanged { | |
val text = it?.toString() ?: "" | |
//當error為null的時候,helper text就會自動顯露出來,但記得不能重複設定error為null,會發生helper text顯示出來又消失的問題,不知之後會不會修正 | |
if (text.length < 6 && !textInputLayout.error.isNullOrEmpty()) { | |
textInputLayout.error = null | |
} else if (text.length > 5 && textInputLayout.error.isNullOrEmpty()){ | |
textInputLayout.error = getString(R.string.limit_exceeded) | |
} | |
} |
就可以達成上面圖片的效果囉~