在 EditText 字段中输入时如何清除错误?

时间:2021-07-07 11:47:49

标签: android kotlin button android-edittext

我有一个包含在 TextInputLayout 中的 EditText 字段。如果您单击“保存”按钮,则此按钮会检查该字段是否已填充:如果是,则一切正常,如果没有,则会出现错误。如果我在出现错误后输入数据,那么我需要再次单击“保存”按钮,以便再次通过完整性检查,然后错误才会消失。我怎样才能使错误在我开始在字段中输入数据时立即消失,并且仅在再次按下按钮时才消失?

private fun checkStateTitleLayout() {
        val titleLayout = findViewById<TextInputLayout>(R.id.editTitleLayout)
        val checkTitleLayoutState = titleLayout.editText?.text?.toString()
        val fieldIsRequired = getString(R.string.fieldIsRequired)
        when {
            checkTitleLayoutState!!.isEmpty() -> {
                titleLayout.error = fieldIsRequired
            }
            else -> {
                titleLayout.error = null
                titleLayout.isErrorEnabled = false
            }
        }
    }

已编辑:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_new_item)

        val saveButton = findViewById<Button>(R.id.saveButton)
        val titleLayout = findViewById<TextInputLayout>(R.id.editTitleLayout)
        titleLayout.editText?.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                titleLayout.error = null
                titleLayout.isErrorEnabled = false
            }
        })

        saveButton.setOnClickListener {
            checkStateTitleLayout()
        }
}

private fun checkStateTitleLayout() {
        val titleLayout = findViewById<TextInputLayout>(R.id.editTitleLayout)
        val checkTitleLayoutState = titleLayout.editText?.text?.toString()
        val fieldIsRequired = getString(R.string.fieldIsRequired)

        if (checkTitleLayoutState!!.isEmpty()) titleLayout.error = fieldIsRequired
    }

1 个答案:

答案 0 :(得分:1)

一种方法是在该 TextWatcher 上使用 EditText。当文本发生变化时,会触发相应的函数并消除错误。

val titleLayout = findViewById<TextInputLayout>(R.id.editTitleLayout)
titleLayout.editText?.addTextChangedListener(object : TextWatcher{
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
    override fun afterTextChanged(s: Editable?) {
        titleLayout.error = null
    }
})

我们只使用 afterTextChanged(),因为在这种情况下只需要它。使用它将使您的应用按预期工作。

相关问题