Hide soft keyboard on losing focus
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);
}
}
}
Android will not hide the keyboard for you. If you want the keyboard to hide when your EditText
loses focus, try using a method like this on that event:
private void hideKeypad() {
EditText edtView = (EditText) findViewById(R.id.e_id);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edtView.getWindowToken(), 0);
}
Try this
/**
* Hide keyboard on touch of UI
*/
public void hideKeyboard(View view) {
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
hideKeyboard(innerView);
}
}
if (!(view instanceof EditText)) {
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(v);
return false;
}
});
}
}
/**
* Hide keyboard while focus is moved
*/
public void hideSoftKeyboard(View view) {
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) contentsContext_
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager != null) {
if (android.os.Build.VERSION.SDK_INT < 11) {
inputManager.hideSoftInputFromWindow(view.getWindowToken(),
0);
} else {
if (this.getCurrentFocus() != null) {
inputManager.hideSoftInputFromWindow(this
.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
view.clearFocus();
}
view.clearFocus();
}
}
}