How can I know when an EditText loses focus?

japuentem picture japuentem · May 16, 2012 · Viewed 144.7k times · Source

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.

Answer

ρяσѕρєя K picture ρяσѕρєя K · May 16, 2012

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
            }
        }
    });