Removing TextChangedListener and then re-adding

So, I tried to implement TextWatcher for Android and ran into several problems when TextChangedListener was called several times or went into an infinite loop, because I want to convert the text in the EditText widget to a string with a formatted currency.

What I did to get around this was to create my own custom TextWatcher, and then the following happened in the afterTextChanged event:

public class CurrencyTextWatcher implements TextWatcher { private EditText et; public CurrencyTextWatcher(EditText editText) { et = editText; } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } public void afterTextChanged(Editable s) { et.removeTextChangedListener(this); et.setText(myCurrencyString); et.addTextChangedListener(this); } } 

So my question is: is there a better way to do this? I want one kind of EditText Widget to hold where the changes go and the resulting formatted string.

Also, are there any other problems associated with removing and adding a TextChangedListener?

Thanks in advance

+6
source share
2 answers

Every time you update (for example, call typing), your editText is called afterTextChanged, so I think you should refrain from calling setText every time you are in afterTextChanged, and only call it when something really changes.

sth like that

 if ( !myCurrencyString.equals(et.getText())) { et.setText(myCurrencyString); } 
+3
source

How about the following.

 private void resetAddTagField() { if (edtView != null && textWatcherListener != null) { edtView.removeTextChangedListener(textWatcherListener); edtView.setText(DEFAULT_TEXT); edtView.addTextChangedListener(textWatcherListener); } } 

What I learn: don't underestimate the power of TextWatcher : D: D

0
source

Source: https://habr.com/ru/post/892971/


All Articles