17

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?

4

2 回答 2

26

onFocusChangehasFocus的实现setOnFocusChangeListener并且有一个布尔参数。如果为 false,则您已经失去了对另一个控件的关注,您应该保存 editext 的数据。例如

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

 editText.setOnFocusChangeListener(new OnFocusChangeListener() {          

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

        }
    });

setOnFocusChangeListener为所有 EditText实现,您也应该处理Back Press事件。如果用户更改了 edittext 的数据并且没有转到另一个 EditText 并按下回,则编辑的值将不会保存。所以应该用onKeyDownor onBackPressedtoo

于 2013-06-20T07:19:12.987 回答
1

由于 Kotlin 现在是官方的 android 语言:

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

editText.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
        if (!hasFocus) { 
           //SAVE THE DATA       
        }
}
于 2020-02-11T09:36:24.597 回答