简体   繁体   English

如何在 Kotlin 的 EditText 中的 4 个字符后添加空格?

[英]How can I add space after 4 character in EditText at Kotlin?

I'm try to make EditText for bank cards.我正在尝试为银行卡制作 EditText。 I need to add space after every 4 number.我需要在每 4 个数字后添加空格。 I already tried another answers at stackoverflow but non of them working for me.我已经在 stackoverflow 尝试了另一个答案,但没有一个对我有用。 I try to make it from count (I use textwatcher) but I can't do it.我尝试从计数(我使用 textwatcher)中做到这一点,但我做不到。 Other answers use insert method for add space but insert method isn't available.其他答案使用插入方法添加空间,但插入方法不可用。 When I write insert it become red so I want to ask for learn.当我写插入它变成红色所以我想要求学习。 How can I make it?我怎样才能做到?

I tried something but I really not know what I'm doing.我尝试了一些东西,但我真的不知道我在做什么。 I really need advices.我真的需要建议。

Here my editText textwatcher code:这是我的editText textwatcher代码:

private val textWatcher = object : TextWatcher {

    override fun afterTextChanged(s: Editable?) {

    }
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
    }
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {


        var txt = s.toString()

        println(txt)
        println(s!!.length)
        if (s!!.length%4 == 0){
            txt = txt + " "
            println(txt)
        }



    }
}

You are creating a text variable not seting the text to the EditText view您正在创建一个未将文本设置为EditText视图的文本变量

txt = txt + " "

You could think that is modifying the text, but primitives and String are immutable so that is another reference in memory, so even if you are trying to us mutability to achieve it won't work.您可能认为这是在修改文本,但原语和字符串是不可变的,因此这是 memory 中的另一个引用,因此即使您尝试通过可变性来实现它也行不通。

if (s!!.length%4 == 0){
    txt = txt + " "
    yourEditText.setText(txt)
}

With EditText you have to use the setter because the field assigned to the text is an Editable so the setText method wraps the conversion from String to Editable使用EditText您必须使用 setter,因为分配给text的字段是Editable的,因此setText方法包装了从StringEditable的转换

There is a common warning regarding this, if I don't miss remember is also on the docs, modifying during a TextWatcher callback can trigger an infinite loop, in this case, it won't because the change to the text will be " filtered " by the condition.对此有一个常见的警告,如果我没有错过,请记住文档上也有,在TextWatcher回调期间进行修改可能会触发无限循环,在这种情况下,不会因为对文本的更改将被“过滤” “按条件。

Just use myedittext.append("") like this像这样使用 myedittext.append("")

if (s...length%4 == 0){ yourEditText.append(" ") }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM