Skip to content

EditTextExtensions

Birju Vachhani edited this page Sep 26, 2019 · 2 revisions

Basics

editText.textString()
editText.toInt()
editText.toFloat()
editText.toLong()
editText.toDouble()

//This one validates emails
editText.isValidEmail()

TextChangedListener

Traditional Way

editText.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(e: Editable?) {
            // do something here
        }

        override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, after: Int) {
            // do something here
        }

        override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {
            // do something here
        }
    })

Extension

editText.textWatcher {
    //Optional
    before = { text, start, count, after ->
        log(text)
    }

    //Optional
    onChanged = { text: CharSequence?, start: Int, before: Int, count: Int ->
        log(text)
    }

    //Optional
    after = { editable ->
        // Don't know what to do here!
    }
}

EditorActionListener

Traditional Way

editText.setOnEditorActionListener { v, actionId, event ->
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            //do something here
        }
        return@setOnEditorActionListener true
    }

Extension

editText.onActionDone(consume = true) { text -> /* Handle Action Done here */ }
editText.onActionNext(consume = true) { text -> /* Handle Action Next here */ }
editText.onActionSearch(consume = true) { text -> /* Handle Action Search here */ }

// handle other actions easily
editText.onActionSearch(action = EditorInfo.IME_ACTION_GO, consume = true) {
    text ->
    log(text)
}

For more information, look at the EditTextExtensions.kt file.