Kotlin addTextChangeListener lambda?

AndroidKotlinTextviewAnko

Android Problem Overview


How do you build a lambda expression for the EditText addTextChangeListener in Kotlin? Below gives an error:

passwordEditText.addTextChangedListener { charSequence  ->
    try {
        password = charSequence.toString()
    } catch (error: Throwable) {
        raise(error)
    }
}

Android Solutions


Solution 1 - Android

addTextChangedListener() takes a TextWatcher which is an interface with 3 methods. What you wrote would only work if TextWatcher had only 1 method. I'm going to guess the error you're getting relates to your lambda not implementing the other 2 methods. You have 2 options going forward.

  1. Ditch the lambda and just use an anonymous inner class
    editText.addTextChangedListener(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) {
      }
    })
  1. Create an extension method so you can use a lambda expression:

    fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
        this.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) {
          }
    
          override fun afterTextChanged(editable: Editable?) {
            afterTextChanged.invoke(editable.toString())
          }
        })
    }

And then use the extension like so:

editText.afterTextChanged { doSomethingWithText(it) }

Solution 2 - Android

Add this core ktx dependence

implementation 'androidx.core:core-ktx:1.0.0'

You simply have to do

passwordEditText.doAfterTextChanged{ }

Solution 3 - Android

A bit old, but using Kotlin Android extensions you can do something like that:

editTextRequest.textChangedListener {
            afterTextChanged {
                // Do something here...
            }
}

No extra code needed, just add:

implementation 'androidx.core:core-ktx:1.0.0'

Solution 4 - Android

Sorry for being late!

If you add implementation 'androidx.core:core-ktx:1.1.0' to your module's build.gradle file then you can use

etPlayer1.doOnTextChanged { text, start, count, after -> // Do stuff }

Solution 5 - Android

hope this Kotlin sample help making it clear:

class MainFragment : Fragment() {
    
    private lateinit var viewModel: MainViewModel

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View {
    val view = inflater.inflate(R.layout.main_fragment, container, false)

    view.user.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) {

        }

        override fun afterTextChanged(s: Editable) {
                userLayout.error =
                        if (s.length > userLayout.counterMaxLength) {
                            "Max character length is: ${userLayout.counterMaxLength}"
                        } else null
        }
    })
    return view
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
    // TODO: Use the ViewModel
   }
}

With this XML layout:

<android.support.design.widget.TextInputLayout
    android:id="@+id/userLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:counterMaxLength="5"
    app:counterEnabled="true"
    android:hint="user_name">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</android.support.design.widget.TextInputLayout>

And this Gradle:

android {
    compileSdkVersion 'android-P'
...
}
    api 'com.android.support:design:28.0.0-alpha1'

    implementation 'com.android.support:appcompat-v7:28.0.0-alpha1' // appcompat library

Solution 6 - Android

Test it :

passwordEditText.addTextChangedListener(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) { }
})

Solution 7 - Android

if you use implementation 'androidx.core:core-ktx:1.1.0-alpha05' you can use

For android.widget.TextView
TextWatcher	
TextView.doBeforeTextChanged(crossinline action: (text: CharSequence?, start: Int, count: Int, after: Int) -> Unit)
Add an action which will be invoked before the text changed.

TextWatcher	
TextView.doOnTextChanged(crossinline action: (text: CharSequence?, start: Int, count: Int, after: Int) -> Unit)
Add an action which will be invoked when the text is changing.

TextWatcher	
TextView.doAfterTextChanged(crossinline action: (text: Editable?) -> Unit)

https://developer.android.com/reference/kotlin/androidx/core/widget/package-summary#extension-functions

Solution 8 - Android

Add the core ktx dependency

implementation 'androidx.core:core-ktx:1.3.0'

And you can simply implement like this

    edit_text.addTextChangedListener { it: Editable? ->
      // Do your stuff here
    }

Solution 9 - Android

In case you're using Material Filled text field or Outlined text field, attempt to respond to input text change as mentioned by documentation, respectively:

filledTextField.editText?.doOnTextChanged { inputText, _, _, _ ->
    // Respond to input text change
}

and

outlinedTextField.editText?.doOnTextChanged { inputText, _, _, _ ->
    // Respond to input text change
}

Solution 10 - Android

Another alternative is the KAndroid library -

implementation 'com.pawegio.kandroid:kandroid:0.8.7@aar'

Then you could do something like this...

editText.textWatcher { afterTextChanged { doSomething() } }

Obviously it is excessive to use an entire library to solve your problem, but it also comes with a range of other useful extensions that eliminate boilerplate code in the Android SDK.

Solution 11 - Android

You can make use of kotlin's named parameters:

private val beforeTextChangedStub: (CharSequence, Int, Int, Int) -> Unit = { _, _, _, _ -> }
private val onTextChangedStub: (CharSequence, Int, Int, Int) -> Unit = { _, _, _, _ -> }
private val afterTextChangedStub: (Editable) -> Unit = {}

fun EditText.addChangedListener(
        beforeTextChanged: (CharSequence, Int, Int, Int) -> Unit = beforeTextChangedStub,
        onTextChanged: (CharSequence, Int, Int, Int) -> Unit = onTextChangedStub,
        afterTextChanged: (Editable) -> Unit = afterTextChangedStub
) = addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
        beforeTextChanged(charSequence, i, i1, i2)
    }

    override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
        onTextChanged(charSequence, i, i1, i2)
    }

    override fun afterTextChanged(editable: Editable) {
        afterTextChanged(editable)
    }
})

Solution 12 - Android

This is the lambda function with edit text field with TextWatcher

searchField.addTextChangedListener(
        afterTextChanged = {

        },
        onTextChanged = {s, start, before, count->
            TODO("DO your code")
        },
        beforeTextChanged = {s, start, before, count->
           TODO("DO your code")
        }
    )

Solution 13 - Android

This looks neat:

passwordEditText.setOnEditorActionListener { 
    textView, keyCode, keyEvent ->
	val DONE = 6
	
    if (keyCode == DONE) {                       
	     // your code here
	}
	false
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLEMUEL ADANEView Question on Stackoverflow
Solution 1 - AndroidAndrew OrobatorView Answer on Stackoverflow
Solution 2 - AndroidAlaaView Answer on Stackoverflow
Solution 3 - AndroidEfi MKView Answer on Stackoverflow
Solution 4 - AndroidtimmyBirdView Answer on Stackoverflow
Solution 5 - AndroidHasan A YousefView Answer on Stackoverflow
Solution 6 - AndroidReza KhammaryView Answer on Stackoverflow
Solution 7 - AndroidingyesidView Answer on Stackoverflow
Solution 8 - AndroidEnzo LizamaView Answer on Stackoverflow
Solution 9 - AndroidFilipe BritoView Answer on Stackoverflow
Solution 10 - AndroidaneurincView Answer on Stackoverflow
Solution 11 - AndroidDmitrii BychkovView Answer on Stackoverflow
Solution 12 - AndroidKawsarView Answer on Stackoverflow
Solution 13 - AndroidLEMUEL ADANEView Answer on Stackoverflow