A simple example to watch or text changed.
((EditText)view.findViewById(R.id.manualCodeEntry)).addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() != 3) { err.setText("Requires 3 letters"); bt.setVisibility(View.INVISIBLE); } else { bt.setVisibility(View.VISIBLE); } } } );
When to use which method (with thanks to stackoverflow):
These events are called in the following order:
- beforeTextChanged(CharSequence s, int start, int count, int after).
This means that the characters are about to be replaced with some new text. The text is uneditable.
Use: when you need to take a look at the old text which is about to change. - onTextChanged(CharSequence s, int start, int before, int count).
Changes have been made, some characters have just been replaced. The text is uneditable.
Use: when you need to see which characters in the text are new. - afterTextChanged(Editable s).
The same as above, except now the text is editable.
Use: when a you need to see and possibly edit new text.
If I’m just listening for changes in EditText
, I won’t need to use the first two methods at all. I will just receive new values in the third method and correct new text if needed. However, if I had to track down exact changes which happen to the values, I would use the first two methods. If I also had a need to edit the text after listening to the changes, I would do that in the third method.