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

How do I clear an error when typing in an EditText field?

我有一个包含在 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
    }

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

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(),因为在这种情况下只需要这样做。使用它将使您的应用按预期工作。