Creating Dynamic Android TextWatcher using Kotlin

abangkis p
2 min readMay 21, 2020

--

Today there’s 1 Pull Request that attract my attention. This code is part of a simple calculator activity. It listen to a field to calculate the total nominal and shows it in a TextView.

Repeat this code for 11 field and you got a large code with lot of empty space and empty implementation. With java, there’s nothing you can do. You just accept it. But with kotlin, code like this become more and more unacceptable.

To fix it we can leverage lambda in kotlin. So I created a DynamicTextWatcher class that extend TextWatcher and implemented all the method. This class constructor accepted 3 lambda that each correlate with a TextWatcher function. This way you can just pass your function without having to implement the other empty function.

But this implementation still requires you to pass empty lambda for the function that you didn’t use. We can again leverage kotlin feature by making the parameter as optional parameter. The only thing we need to do is giving the parameters default value.

Thus now the code can be called like this

A whole lot of line has gone. Code that doesn’t matter, boiler plate. Now we an focus directly to the code that matters.

Turn out the original coder has done a good job of centralizing the calculation. So we can extract the onChanged into a single val resulting the final code to become like this

138 line of code reduced to 24 line in minutes.

They say programming language is only a tool. But choosing the right tool can save you a lot of work.

Turn out this already exist as Android-ktx implementation. The implementation is quite similar. So it’s interesting to see the difference.

See the ktx implementation here. To use the ktx implementation the code needs to be modified to be like this:

--

--

abangkis p
abangkis p

Written by abangkis p

Founder of MReunion Labs. Senior Developer Id-Android. Take a chance! Click that follow button.