Android - Do something *after* text is changed in EditText

TamarG picture TamarG · Jun 20, 2013 · Viewed 19.5k times · Source

I build an android application. I have an EditText. I want to save changes (or anything else) automatically after the user change the text. Now I use

editText.addTextChangedListener(textWatcher);

and

  TextWatcher textWatcher = new TextWatcher() {
    public void afterTextChanged(Editable s) {
     ...
    }

But it saves the changes after every little change (add \ remove a letter), and I want that it'll be saved only after the user finished (closed the keyboard, clicked on a different edittext, etc. ). How can I do that?

Answer

Pankaj Kumar picture Pankaj Kumar · Jun 20, 2013

Implement onFocusChange of setOnFocusChangeListener and there's a boolean parameter for hasFocus. When this is false, you've lost focus to another control and you should save the data of editext. for example

 EditText editText= (EditText) findViewById(R.id.editText);

 editText.setOnFocusChangeListener(new OnFocusChangeListener() {          

        public void onFocusChange(View v, boolean hasFocus) {
            if(!hasFocus) {
                //SAVE THE DATA 
            }  

        }
    });

Implement setOnFocusChangeListener for all EditTexts and you should handle Back Press event too. If the user change the data of edittext and didn't goto another EditText and pressed back then edited vallue will not save. So should use onKeyDown or onBackPressed too