Android: Close the virtual "on-screen" keyboard

There was a slight quirk that I ran into while working on my app. If I were editing text and clicked "Save" on the activity, it'd close the screen but keep the keyboard open.

I'd then have to press the BACK button to close it. A small but somewhat irritating quirk. Luckily, its an easy thing to fix.

First, define an "OnFocusChangeListener":

private OnFocusChangeListener hideKeyboard = new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

When you're creating and setting up your edit boxes, just set the following listeners:


There you have it. It should now hide the keyboard automatically.

If no other objects take focus, then just call the listener manually.

hideKeyboard.onFocusChange(txtUsername, false);
hideKeyboard.onFocusChange(txtEmail, false);

[ Source ]

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog