Enamul Haque
Enamul Haque

Reputation: 5053

EditText settext on addTextChangedListener(TextWatcher) infite loop in Kotlin

I am using Kotlin. I need check EditText value & add some logic to the value & set the value to same EditText every character. But unfortunately it is going infinite loop. I have use bellow code.

    EditText amount_txtAmount = findViewById(R.id.amount_txtAmount)

    amount_txtAmount.addTextChangedListener(object : TextWatcher {
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

        }

        override fun afterTextChanged(s: Editable) {
            if (amount_txtAmount.text.toString().length > 0) {

                    var amount1 =   ValidationUtil.commaSeparateAmount(amount_txtAmount.text.toString())
                    Log.e("formatAmount-->", amount1)
                    amount_txtAmount.setText(amount1)                   

           }
        }
    })

Please help how to overcome infinite loop.

Upvotes: 0

Views: 652

Answers (3)

Francesc
Francesc

Reputation: 29260

I'm not certain manipulating the text in the callback is the best solution, but if you want to do it, a possible way to fix the infinite loop is to remove and add the listener

    override fun afterTextChanged(s: Editable) {
        if (amount_txtAmount.text.toString().length > 0) {

            amount_txtAmount.removeTextChangedListener(this)
            var amount1 =   ValidationUtil.commaSeparateAmount(amount_txtAmount.text.toString())
            Log.e("formatAmount-->", amount1)
            amount_txtAmount.setText(amount1)                   
            amount_txtAmount.addTextChangedListener(this)
        }
    }

Upvotes: 3

Jaime
Jaime

Reputation: 388

Validating the user input inside a text watcher might not be the best solution. Maybe you could simply validate after the user has definitely finished with the editText. A couple of options could be

1) Validate on edit text lost focus

2) Have a validate button

Upvotes: 0

Dinh Lam
Dinh Lam

Reputation: 765

var amount1 = ValidationUtil.commaSeparateAmount(amount_txtAmount.text.toString())
Log.e("formatAmount-->", amount1)
amount_txtAmount.setText(amount1)

This is a reason, if you need to constraint length of input you can set InputFilter to you EditText to make user can not input greater some value.

Upvotes: 0

Related Questions