Kotlin addTextChangeListener lambda?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







50















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)
}
}









share|improve this question




















  • 2





    What error does it gives?

    – voddan
    Nov 13 '16 at 10:24


















50















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)
}
}









share|improve this question




















  • 2





    What error does it gives?

    – voddan
    Nov 13 '16 at 10:24














50












50








50


7






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)
}
}









share|improve this question
















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 textview kotlin android-textview anko






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 '18 at 18:52









Andrew Orobator

3,71212032




3,71212032










asked Nov 13 '16 at 1:00









LEMUEL ADANELEMUEL ADANE

2,544103259




2,544103259








  • 2





    What error does it gives?

    – voddan
    Nov 13 '16 at 10:24














  • 2





    What error does it gives?

    – voddan
    Nov 13 '16 at 10:24








2




2





What error does it gives?

– voddan
Nov 13 '16 at 10:24





What error does it gives?

– voddan
Nov 13 '16 at 10:24












7 Answers
7






active

oldest

votes


















141














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(p0: Editable?) {
}

override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}

override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
})


2) Create an extension method so you can use a lambda expression:



fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
this.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}

override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}

override fun afterTextChanged(editable: Editable?) {
afterTextChanged.invoke(editable.toString())
}
})
}


And then use the extension like so:



editText.afterTextChanged { doSomethingWithText(it) }





share|improve this answer





















  • 2





    Not sure if personal preference or better style, but your extension function could be converted to an expression body (fun foo() = ...)

    – F. George
    Nov 13 '16 at 16:41






  • 2





    @mEQ5aNLrK3lqs3kfSa5HbvsTWe0nIu You're right that it can be converted. However, for functions longer than one line, I like having surrounding brackets to clearly mark where the function starts and stops. I believe it increases readability, but it's totally a style preference. I think it could be argued both ways :)

    – Andrew Orobator
    Nov 13 '16 at 18:16






  • 1





    @LEM Adane please accept this answer if it helped you.

    – Andrew Orobator
    Aug 11 '17 at 19:21



















8














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





share|improve this answer































    5














    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'





    share|improve this answer





















    • 1





      That's not working for me, even after refactoring to android X. Any guess to what I could be doing wrong?

      – Nícolas Schirmer
      Oct 16 '18 at 1:50








    • 2





      Does not work for me as well. It looks like KTX does not provide this extension anymore, however, KAndroid solution works perfectly.

      – Igor Wojda
      Nov 27 '18 at 13:58













    • with ktx:1.0.1 you can use developer.android.com/reference/kotlin/androidx/core/widget/…

      – ingyesid
      Apr 4 at 19:52



















    1














    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.






    share|improve this answer

































      0














      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






      share|improve this answer

































        0














        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)
        }
        })





        share|improve this answer








        New contributor




        Dmitrii Bychkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.




























          -6














          This looks neat:



          passwordEditText.setOnEditorActionListener { 
          textView, keyCode, keyEvent ->
          val DONE = 6

          if (keyCode == DONE) {
          // your code here
          }
          false
          }





          share|improve this answer


























          • youf, this worked for me

            – LEMUEL ADANE
            Jan 30 at 14:51












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40569436%2fkotlin-addtextchangelistener-lambda%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          141














          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(p0: Editable?) {
          }

          override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }
          })


          2) Create an extension method so you can use a lambda expression:



          fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
          this.addTextChangedListener(object : TextWatcher {
          override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun afterTextChanged(editable: Editable?) {
          afterTextChanged.invoke(editable.toString())
          }
          })
          }


          And then use the extension like so:



          editText.afterTextChanged { doSomethingWithText(it) }





          share|improve this answer





















          • 2





            Not sure if personal preference or better style, but your extension function could be converted to an expression body (fun foo() = ...)

            – F. George
            Nov 13 '16 at 16:41






          • 2





            @mEQ5aNLrK3lqs3kfSa5HbvsTWe0nIu You're right that it can be converted. However, for functions longer than one line, I like having surrounding brackets to clearly mark where the function starts and stops. I believe it increases readability, but it's totally a style preference. I think it could be argued both ways :)

            – Andrew Orobator
            Nov 13 '16 at 18:16






          • 1





            @LEM Adane please accept this answer if it helped you.

            – Andrew Orobator
            Aug 11 '17 at 19:21
















          141














          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(p0: Editable?) {
          }

          override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }
          })


          2) Create an extension method so you can use a lambda expression:



          fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
          this.addTextChangedListener(object : TextWatcher {
          override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun afterTextChanged(editable: Editable?) {
          afterTextChanged.invoke(editable.toString())
          }
          })
          }


          And then use the extension like so:



          editText.afterTextChanged { doSomethingWithText(it) }





          share|improve this answer





















          • 2





            Not sure if personal preference or better style, but your extension function could be converted to an expression body (fun foo() = ...)

            – F. George
            Nov 13 '16 at 16:41






          • 2





            @mEQ5aNLrK3lqs3kfSa5HbvsTWe0nIu You're right that it can be converted. However, for functions longer than one line, I like having surrounding brackets to clearly mark where the function starts and stops. I believe it increases readability, but it's totally a style preference. I think it could be argued both ways :)

            – Andrew Orobator
            Nov 13 '16 at 18:16






          • 1





            @LEM Adane please accept this answer if it helped you.

            – Andrew Orobator
            Aug 11 '17 at 19:21














          141












          141








          141







          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(p0: Editable?) {
          }

          override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }
          })


          2) Create an extension method so you can use a lambda expression:



          fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
          this.addTextChangedListener(object : TextWatcher {
          override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun afterTextChanged(editable: Editable?) {
          afterTextChanged.invoke(editable.toString())
          }
          })
          }


          And then use the extension like so:



          editText.afterTextChanged { doSomethingWithText(it) }





          share|improve this answer















          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(p0: Editable?) {
          }

          override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }
          })


          2) Create an extension method so you can use a lambda expression:



          fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
          this.addTextChangedListener(object : TextWatcher {
          override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
          }

          override fun afterTextChanged(editable: Editable?) {
          afterTextChanged.invoke(editable.toString())
          }
          })
          }


          And then use the extension like so:



          editText.afterTextChanged { doSomethingWithText(it) }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 13 '16 at 18:11

























          answered Nov 13 '16 at 1:57









          Andrew OrobatorAndrew Orobator

          3,71212032




          3,71212032








          • 2





            Not sure if personal preference or better style, but your extension function could be converted to an expression body (fun foo() = ...)

            – F. George
            Nov 13 '16 at 16:41






          • 2





            @mEQ5aNLrK3lqs3kfSa5HbvsTWe0nIu You're right that it can be converted. However, for functions longer than one line, I like having surrounding brackets to clearly mark where the function starts and stops. I believe it increases readability, but it's totally a style preference. I think it could be argued both ways :)

            – Andrew Orobator
            Nov 13 '16 at 18:16






          • 1





            @LEM Adane please accept this answer if it helped you.

            – Andrew Orobator
            Aug 11 '17 at 19:21














          • 2





            Not sure if personal preference or better style, but your extension function could be converted to an expression body (fun foo() = ...)

            – F. George
            Nov 13 '16 at 16:41






          • 2





            @mEQ5aNLrK3lqs3kfSa5HbvsTWe0nIu You're right that it can be converted. However, for functions longer than one line, I like having surrounding brackets to clearly mark where the function starts and stops. I believe it increases readability, but it's totally a style preference. I think it could be argued both ways :)

            – Andrew Orobator
            Nov 13 '16 at 18:16






          • 1





            @LEM Adane please accept this answer if it helped you.

            – Andrew Orobator
            Aug 11 '17 at 19:21








          2




          2





          Not sure if personal preference or better style, but your extension function could be converted to an expression body (fun foo() = ...)

          – F. George
          Nov 13 '16 at 16:41





          Not sure if personal preference or better style, but your extension function could be converted to an expression body (fun foo() = ...)

          – F. George
          Nov 13 '16 at 16:41




          2




          2





          @mEQ5aNLrK3lqs3kfSa5HbvsTWe0nIu You're right that it can be converted. However, for functions longer than one line, I like having surrounding brackets to clearly mark where the function starts and stops. I believe it increases readability, but it's totally a style preference. I think it could be argued both ways :)

          – Andrew Orobator
          Nov 13 '16 at 18:16





          @mEQ5aNLrK3lqs3kfSa5HbvsTWe0nIu You're right that it can be converted. However, for functions longer than one line, I like having surrounding brackets to clearly mark where the function starts and stops. I believe it increases readability, but it's totally a style preference. I think it could be argued both ways :)

          – Andrew Orobator
          Nov 13 '16 at 18:16




          1




          1





          @LEM Adane please accept this answer if it helped you.

          – Andrew Orobator
          Aug 11 '17 at 19:21





          @LEM Adane please accept this answer if it helped you.

          – Andrew Orobator
          Aug 11 '17 at 19:21













          8














          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





          share|improve this answer




























            8














            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





            share|improve this answer


























              8












              8








              8







              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





              share|improve this answer













              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






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jun 1 '18 at 22:18









              Hasan A YousefHasan A Yousef

              6,13544072




              6,13544072























                  5














                  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'





                  share|improve this answer





















                  • 1





                    That's not working for me, even after refactoring to android X. Any guess to what I could be doing wrong?

                    – Nícolas Schirmer
                    Oct 16 '18 at 1:50








                  • 2





                    Does not work for me as well. It looks like KTX does not provide this extension anymore, however, KAndroid solution works perfectly.

                    – Igor Wojda
                    Nov 27 '18 at 13:58













                  • with ktx:1.0.1 you can use developer.android.com/reference/kotlin/androidx/core/widget/…

                    – ingyesid
                    Apr 4 at 19:52
















                  5














                  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'





                  share|improve this answer





















                  • 1





                    That's not working for me, even after refactoring to android X. Any guess to what I could be doing wrong?

                    – Nícolas Schirmer
                    Oct 16 '18 at 1:50








                  • 2





                    Does not work for me as well. It looks like KTX does not provide this extension anymore, however, KAndroid solution works perfectly.

                    – Igor Wojda
                    Nov 27 '18 at 13:58













                  • with ktx:1.0.1 you can use developer.android.com/reference/kotlin/androidx/core/widget/…

                    – ingyesid
                    Apr 4 at 19:52














                  5












                  5








                  5







                  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'





                  share|improve this answer















                  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'






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 16 '18 at 15:39









                  Krasavello13

                  434




                  434










                  answered May 24 '18 at 8:42









                  Efi MKEfi MK

                  445519




                  445519








                  • 1





                    That's not working for me, even after refactoring to android X. Any guess to what I could be doing wrong?

                    – Nícolas Schirmer
                    Oct 16 '18 at 1:50








                  • 2





                    Does not work for me as well. It looks like KTX does not provide this extension anymore, however, KAndroid solution works perfectly.

                    – Igor Wojda
                    Nov 27 '18 at 13:58













                  • with ktx:1.0.1 you can use developer.android.com/reference/kotlin/androidx/core/widget/…

                    – ingyesid
                    Apr 4 at 19:52














                  • 1





                    That's not working for me, even after refactoring to android X. Any guess to what I could be doing wrong?

                    – Nícolas Schirmer
                    Oct 16 '18 at 1:50








                  • 2





                    Does not work for me as well. It looks like KTX does not provide this extension anymore, however, KAndroid solution works perfectly.

                    – Igor Wojda
                    Nov 27 '18 at 13:58













                  • with ktx:1.0.1 you can use developer.android.com/reference/kotlin/androidx/core/widget/…

                    – ingyesid
                    Apr 4 at 19:52








                  1




                  1





                  That's not working for me, even after refactoring to android X. Any guess to what I could be doing wrong?

                  – Nícolas Schirmer
                  Oct 16 '18 at 1:50







                  That's not working for me, even after refactoring to android X. Any guess to what I could be doing wrong?

                  – Nícolas Schirmer
                  Oct 16 '18 at 1:50






                  2




                  2





                  Does not work for me as well. It looks like KTX does not provide this extension anymore, however, KAndroid solution works perfectly.

                  – Igor Wojda
                  Nov 27 '18 at 13:58







                  Does not work for me as well. It looks like KTX does not provide this extension anymore, however, KAndroid solution works perfectly.

                  – Igor Wojda
                  Nov 27 '18 at 13:58















                  with ktx:1.0.1 you can use developer.android.com/reference/kotlin/androidx/core/widget/…

                  – ingyesid
                  Apr 4 at 19:52





                  with ktx:1.0.1 you can use developer.android.com/reference/kotlin/androidx/core/widget/…

                  – ingyesid
                  Apr 4 at 19:52











                  1














                  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.






                  share|improve this answer






























                    1














                    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.






                    share|improve this answer




























                      1












                      1








                      1







                      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.






                      share|improve this answer















                      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.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Aug 15 '18 at 13:16

























                      answered Aug 24 '17 at 8:05









                      ASC500ASC500

                      706514




                      706514























                          0














                          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






                          share|improve this answer






























                            0














                            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






                            share|improve this answer




























                              0












                              0








                              0







                              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






                              share|improve this answer















                              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







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Apr 4 at 20:12

























                              answered Apr 4 at 19:57









                              ingyesidingyesid

                              2,34011619




                              2,34011619























                                  0














                                  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)
                                  }
                                  })





                                  share|improve this answer








                                  New contributor




                                  Dmitrii Bychkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.

























                                    0














                                    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)
                                    }
                                    })





                                    share|improve this answer








                                    New contributor




                                    Dmitrii Bychkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.























                                      0












                                      0








                                      0







                                      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)
                                      }
                                      })





                                      share|improve this answer








                                      New contributor




                                      Dmitrii Bychkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.










                                      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)
                                      }
                                      })






                                      share|improve this answer








                                      New contributor




                                      Dmitrii Bychkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.









                                      share|improve this answer



                                      share|improve this answer






                                      New contributor




                                      Dmitrii Bychkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.









                                      answered Apr 5 at 12:06









                                      Dmitrii BychkovDmitrii Bychkov

                                      411




                                      411




                                      New contributor




                                      Dmitrii Bychkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.





                                      New contributor





                                      Dmitrii Bychkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.






                                      Dmitrii Bychkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.























                                          -6














                                          This looks neat:



                                          passwordEditText.setOnEditorActionListener { 
                                          textView, keyCode, keyEvent ->
                                          val DONE = 6

                                          if (keyCode == DONE) {
                                          // your code here
                                          }
                                          false
                                          }





                                          share|improve this answer


























                                          • youf, this worked for me

                                            – LEMUEL ADANE
                                            Jan 30 at 14:51
















                                          -6














                                          This looks neat:



                                          passwordEditText.setOnEditorActionListener { 
                                          textView, keyCode, keyEvent ->
                                          val DONE = 6

                                          if (keyCode == DONE) {
                                          // your code here
                                          }
                                          false
                                          }





                                          share|improve this answer


























                                          • youf, this worked for me

                                            – LEMUEL ADANE
                                            Jan 30 at 14:51














                                          -6












                                          -6








                                          -6







                                          This looks neat:



                                          passwordEditText.setOnEditorActionListener { 
                                          textView, keyCode, keyEvent ->
                                          val DONE = 6

                                          if (keyCode == DONE) {
                                          // your code here
                                          }
                                          false
                                          }





                                          share|improve this answer















                                          This looks neat:



                                          passwordEditText.setOnEditorActionListener { 
                                          textView, keyCode, keyEvent ->
                                          val DONE = 6

                                          if (keyCode == DONE) {
                                          // your code here
                                          }
                                          false
                                          }






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Jul 17 '18 at 15:23

























                                          answered Nov 13 '16 at 2:16









                                          LEMUEL ADANELEMUEL ADANE

                                          2,544103259




                                          2,544103259













                                          • youf, this worked for me

                                            – LEMUEL ADANE
                                            Jan 30 at 14:51



















                                          • youf, this worked for me

                                            – LEMUEL ADANE
                                            Jan 30 at 14:51

















                                          youf, this worked for me

                                          – LEMUEL ADANE
                                          Jan 30 at 14:51





                                          youf, this worked for me

                                          – LEMUEL ADANE
                                          Jan 30 at 14:51


















                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40569436%2fkotlin-addtextchangelistener-lambda%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          List item for chat from Array inside array React Native

                                          Thiostrepton

                                          Caerphilly