Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 880
TamarG Avatar asked Jun 20 '13 07:06

TamarG


People also ask

Why we use TextWatcher in android?

Stay organized with collections Save and categorize content based on your preferences. Base class that can be used to implement virtualized lists of items. A view that shows items in a vertically scrolling two-level list.

What is TextWatcher?

TextWatcher is a useful class provided by the Android Developer API. It can be used to watch a input text field and you can instantly update data on other views. It can be useful for counting the number of characters entered in the text field instantly and measuring password strength on entering etc.

How do I use addTextChangedListener?

You should create a Listener class like so, Just modify the parameters in the constructor to accept the EditText ID you want to add a listener to. mobileNumber2. addTextChangedListener(new addListenerOnTextChange(this, mobileNumber2)); Again modify the parameters as needed.


1 Answers

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

like image 196
Pankaj Kumar Avatar answered Sep 25 '22 12:09

Pankaj Kumar