giovedì 4 febbraio 2010

Android: Get events when an edit text content changes

This is a problem not very well documented by Google but it is a common task the developers have to do often.

The solution is use a TextWatcher object that will receive event when the text in the EditText changes:

// Watcher to chage char counter when sms text changes
TextWatcher textWatcher = new TextWatcher() {
    @Override
    public void onTextChanged ( CharSequence arg0, int arg1, int arg2, int arg3 ) {
    }

    @Override public void beforeTextChanged ( CharSequence arg0, int arg1, int arg2,  int arg3 ) {
    }

    @Override
    public void afterTextChanged ( Editable arg0 ) {
         updateCharCounter(); }
    };

m_smsTextField.addTextChangedListener(textWatcher);