androidandroid-edittextlostfocus

How can I know when an EditText loses focus?


I need to catch when an EditText loses focus, I've searched other questions but I didn't find an answer.

I used OnFocusChangeListener like this

OnFocusChangeListener foco = new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        // TODO Auto-generated method stub

    }
};

But, it doesn't work for me.


Solution

  • Implement onFocusChange of setOnFocusChangeListener and there's a boolean parameter for hasFocus. When this is false, you've lost focus to another control.

     EditText txtEdit = (EditText) findViewById(R.id.edittxt);
    
     txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {          
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                   // code to execute when EditText loses focus
                }
            }
        });