Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

As Kotlin is now official android language:

var editText = findViewById<EditText>(R.id.editText) 

editText.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
        if (!hasFocus) { 
           //SAVE THE DATA       
        }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top