在addTextChangedListener中将editText文本设置为大写会导致应用程序挂起

4
我想即使用户输入小写字母,也要将edittext的内容改为大写。因此,我会在addTextChangedListener上设置ediText文本转换为大写,如下所示。
  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) {
                    editText.setText(s.toString().toUpperCase())
            }

            override fun afterTextChanged(s : Editable?) {

            }
    })

但是当我在editText中输入内容时,应用程序会挂起,我必须杀死应用程序并重新启动它。由于我想在绑定适配器中使用它,所以我不能使用xml的AllCaps方法。


你为什么不使用InputType方法并将textCapCharacters分配给它呢? - Gorks
1
这个回答解决了你的问题吗?如何将Android EditText中的每个字母都大写? - Cliff
欢迎来到Stackoverflow。我看到你在问题陈述中已经很明确了,但是如果你想得到答案,你的问题还需要做一些修改。请参考如何提问并相应地更新你的问题。 - Ortund
2个回答

1

在编辑EditText的文本之前,您需要删除textwatcher,并在更改完成后重新添加它。

    val watcher: TextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            editText.removeTextChangedListener(this)
            editText.setText(s.toString().toUpperCase())
            editText.addTextChangedListener(this)
        }

        override fun afterTextChanged(s: Editable) {}
    }

    editText.addTextChangedListener(watcher)

1
你可以在xml中或者通过编程使用输入类型。
editText.inputType == InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS

在你的XML中,你可以放置以下内容:

android:inputType="textCapCharacters"

这个解决方案将自动将输入转换为大写字母


是的,但我想将这个方法添加到绑定适配器中。 - Purvesh Dodiya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接