Hiding SoftKeyboard
suggest changeHiding the soft keyboard is a common need when working with an EditText. By default it closes when the user presses Back. InputMethodManager can hide it sooner. Call hideSoftInputFromWindow with the token of the focused view:
public void hideSoftKeyboard() {
View focused = getCurrentFocus();
if (focused == null) {
return;
}
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(focused.getWindowToken(), 0);
}
The hide call still has to run when some event occurs. To hide the keyboard on a tap outside the EditText, call the following once from onCreate(). It only sees the view tree that exists at that moment. Views added later need the same setup.
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard();
return false;
}
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents