要创建一个Anko自定义小部件,可以使用TextInputLayout
来显示编辑文本,并使用setErrorEnabled(false)
方法来隐藏错误文本。下面是一个示例代码:
class NoErrorTextInputLayout(context: Context) : TextInputLayout(context) {
private var editText: EditText? = null
init {
createEditText()
}
private fun createEditText() {
editText = EditText(context)
addView(editText)
}
fun setText(text: CharSequence?) {
editText?.setText(text)
}
fun getText(): CharSequence? {
return editText?.text
}
fun setErrorEnabled(enabled: Boolean) {
super.setErrorEnabled(false)
}
fun setError(error: CharSequence?) {
// Do nothing to hide error text
}
}
使用这个自定义小部件,可以像下面这样在Anko布局中使用它:
verticalLayout {
val noErrorTextInputLayout = NoErrorTextInputLayout(context)
noErrorTextInputLayout.hint = "Enter text"
addView(noErrorTextInputLayout)
}
在代码中,可以使用noErrorTextInputLayout.setText(text)
和noErrorTextInputLayout.getText()
来设置和获取编辑文本的值。调用noErrorTextInputLayout.setErrorEnabled(false)
方法来隐藏错误文本,调用noErrorTextInputLayout.setError(error)
方法不会显示错误文本。