문제

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?

도움이 되었습니까?

해결책

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

다른 팁

As Kotlin is now official android language:

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

editText.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
        if (!hasFocus) { 
           //SAVE THE DATA       
        }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top