【问题标题】:Set editText text to upper case on addTextChangedListener making app hang [closed]在 addTextChangedListener 上将editText文本设置为大写,使应用程序挂起[关闭]
【发布时间】:2021-04-08 16:32:31
【问题描述】:

即使用户在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 方法

p>

【问题讨论】:

  • 为什么不使用InputType 方法并将textCapCharacters 分配给它?
  • 欢迎来到 Stackoverflow。我看到您的问题中有一个可靠的问题陈述,但是如果您想获得答案,您的问题仍然需要进行一些更改。请参阅how to ask 并适当更新您的问题。

标签: android firebase kotlin android-edittext


【解决方案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)

【讨论】:

    【解决方案2】:

    您可以在 xml 中或以编程方式使用 Input 类型。

    editText.inputType == InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
    

    在你的xml中你可以放

    android:inputType="textCapCharacters"
    

    此解决方案会自动将输入转换为大写

    【讨论】:

    • 是的,但是我想在绑定适配器中添加这个方法
    猜你喜欢
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 2012-08-16
    • 2010-12-12
    • 2013-01-20
    • 2014-07-12
    • 1970-01-01
    • 2015-03-02
    相关资源
    最近更新 更多