In android you can apply TextWatcher on an EditText and perform action based on changes in the EditText. It is particularly useful when you want to perform some action while the user is entering text like auto save feature of text or suggestion feature. So in that case we can apply a TextWatcher and attach the methods we want to perform on text change.
There are three methods of TextWatcher we can use based on our need.
a. beforeTextChanged( CharSequence s, int start, int count, int after )
This method is used to notify you that in the CharSequence s, count number of character that start at start are about to be changed with a new text having after number of characters.
b. onTextChanged( CharSequence s, int start, int before, int count)
It is just the reverse of earlier one. This method is used to notify you that in the CharSequence s, count number of character that start at start are already been changed with older text having before number of characters.
c. afterTextChanged(Editable s)
It is the mostly used method as it performs after the text is changed and we generally have to perform something when the text is changes like saving it for the user. Some people perform text changes in this method and if you do so be careful that you don’t end up in an infinite loop as after any change to the text this method is again called.
I had used it to save the value of the text so that the user always get the updated value and loss of the data can be prevented. Below is the dummy code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
EditText mEditText = (EditText) findViewById(R.id.edit_text); mEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { if (editable.length() != 0) { // save the content here } } }); |