Android: How to Hide Keyboard By Touching Screen Outside Keyboard

If you’ve ever worked for a mobile software company that builds both an iOS app and an Android app, many times the product people will ask that a certain feature be implemented consistently across both platforms.  This week I was tasked with implementing a popular iOS feature, the ability to hide the virtual keyboard when the user touches outside of the keyboard, on Android.

The methodology is simple, but not entirely intuitive. Let’s look at how it’s done. Basically, you get a handle on the layout in question. In this example, we’ll use a LinearLayout:

LinearLayout layout = (LinearLayout) findViewById(R.id.layout);

 

Then, override the layout’s OnTouchListener.onTouch() like so:

layout.setOnTouchListener(new OnTouchListener()
{
    @Override
    public boolean onTouch(View view, MotionEvent ev)
    {
        hideKeyboard(view);
        return false;
    }
});

 

The code to hide the keyboard is fairly popular:

/**
* Hides virtual keyboard
*
* @author kvarela
*/
protected void hideKeyboard(View view)
{
    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    in.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

One thought on “Android: How to Hide Keyboard By Touching Screen Outside Keyboard