Ascorbin Ascorbin - 3 months ago 43
Android Question

Hide soft keyboard on losing focus

When we have an

EditText
and it loses focus (to an element that doesn't need a keyboard), should the soft keyboard hide automatically or are we supposed to hide it ourselves?

I'm moving the focus from an
AutoCompleteSearchView
(which should behave like an
EditText
I guess) to a
Button
,
requestFocus()
returns true, but the keyboard doesn't hide.

Answer

Best way is to set a OnFocusChangeListener for the EditText, and then add the code to the the keyboard into the OnFocusChange method of the listener. Android will then automatically close the keyboard when the EditText loses focus.

Something like this in your OnCreate method:

EditText editText = (EditText) findViewById(R.id.textbox);
OnFocusChangeListener ofcListener = new MyFocusChangeListener();
editText.setOnFocusChangeListener(ofcListener);

and then add the class:

private class MyFocusChangeListener implements OnFocusChangeListener {

    public void onFocusChange(View v, boolean hasFocus){

        if(v.getId() == R.id.textbox && !hasFocus) {

            InputMethodManager imm =  (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

        }
    }
}