Updated 31 July 2020
TextWatcher
EditText uses TextWatcher interface to watch change made over EditText. For doing this, EditText calls the addTextChangedListener() method.
In this way, we can check all change while modify text in EditText in android. But if there is need to check multiple EditText in single screen, then we have to add
multiple TextWatcher for every EditText and manage a lot of lines. So we can make dynamic TextWatcher, that solve our problems.
Dynamic TextWatcher:-
In DynamicTextWatcher, we have to extends TextWatcher class and override its methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class DynamicTextWatcher( private val afterChanged: (Editable?) -> Unit, private val beforeChanged: (CharSequence?, Int, Int, Int) -> Unit, private val onChanged: (CharSequence?, Int, Int, Int) -> Unit ) : TextWatcher { override fun afterTextChanged(s: Editable?) { afterChanged(s) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { beforeChanged(s, start, count, after) } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { onChanged(s, start, before, count) } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class DynamicTextWatcher( private val afterChanged: ((Editable?) -> Unit) = {}, private val beforeChanged: ((CharSequence?, Int, Int, Int) -> Unit) = { _, _, _, _ -> }, private val onChanged: ((CharSequence?, Int, Int, Int) -> Unit) = { _, _, _, _ -> } ) : TextWatcher { override fun afterTextChanged(s: Editable?) { afterChanged(s) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { beforeChanged(s, start, count, after) } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { onChanged(s, start, before, count) } } |
Thus, we can use it for any edit_text like this:-
1 2 3 4 5 |
edit_text.addTextChangedListener(DynamicTextWatcher( onChanged = { _, _, _, _ -> // do your code here } )) |
In this way, we can rectify a lot of boilerplate code from our class and it will also look pretty.
We can do more centralize code and extract the onChanged into a single val resulting the final code to become like this:-
1 2 3 4 5 6 7 8 9 |
val textWatcher = DynamicTextWatcher( onChanged = { _, _, _, _ -> // do your code }) edittext1.addTextChangedListener(textWatcher) edittext2.addTextChangedListener(textWatcher) edittext3.addTextChangedListener(textWatcher) edittext4.addTextChangedListener(textWatcher) |
For more detail, you can reference:-
https://developer.android.com/reference/android/text/TextWatcher
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.