DEV Community

Cover image for You Could Write Simpler Code in Android: Monitoring Changed Text in An EditText Field
Samuel Ochuba
Samuel Ochuba

Posted on • Edited on

2 1

You Could Write Simpler Code in Android: Monitoring Changed Text in An EditText Field

While working on my recent project, several times while trying to implement a feature I came across several articles online whose code advocated writing long lines of code. This could be as a result of the articles being written a long time ago(In android, a long time could be as short as six months). This informed my choice to create a series where I highlight simpler ways of writing code than the ones commonly available online when using ktx extensions.

This article is going to be a short one just to illustrate how much fewer lines of code you could write. A particular scenario you might be faced with is getting the changing text when a user inputs value into an edittext field. The situation might also mean you want a particular event to occur anytime the text in the field changes.

To accomplish this task, a cursory search on google might take you to a stackoverflow page where the top three answers may look like this one:

Alt Text

Or this one:

Alt Text

After seeing these answers you get the feeling that you are writing a lot of code just to get the text that was changed or to be notified when the text changes. Don't worry I get the feeling. I had the same exact feeling

I discovered that it could be accomplished with just three lines of code. A call to the doOnTextChanged was enough to do my bidding.

var myEditText = findViewById<EditText>(R.id.myEditText)
myEditText.doOnTextChanged { text, start, before, count ->
run {
// run your code here.
// the text is the changed text
}
}
view raw edit.kt hosted with ❤ by GitHub

My next article would be on Navigation drawer stay tuned

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay