0

I want to write TextWatcher for several EditTexts. In any of them I want to assign EditText value to a variable. Like this:

var variable: String? = null

private inner class CodeTextWatcher : TextWatcher {
    override fun afterTextChanged(s: Editable?) {
        variable = s?.toString()
    }

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

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

For several EditTexts I want to write something like:

private inner class CodeTextWatcher(private val method: (String?) -> Unit) : TextWatcher {
    override fun afterTextChanged(s: Editable?) {
        method(s?.toString())
    }

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

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

and call it:

textWatcher1 = CodeTextWatcher {variable1 = s}
textWatcher2 = CodeTextWatcher {variable2 = s}

But I cannot write s here and want to access s from afterTextChanged(s: Editable?). Is it possible?

1 Answer 1

3

Have you tried:

textWatcher1 = CodeTextWatcher { s -> variable1 = s }
textWatcher2 = CodeTextWatcher { s -> variable2 = s }

Or in this case, maybe even

textWatcher1 = CodeTextWatcher { variable1 = it }
textWatcher2 = CodeTextWatcher { variable2 = it }

?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.