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(;


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

layout.setOnTouchListener(new OnTouchListener()
    public boolean onTouch(View view, MotionEvent ev)
        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);

Android FrameLayout Example

The Android FrameLayout is one of the lesser used layouts in the Android system, but it definitely has its purposes. The main reason you’d use a FrameLayout is when you only want to show one View at a time inside that FrameLayout. You can think of the Views as if they were in a stack with the most recently added View at the top.
Let’s walk through a simple example. The following code will first draw a red square with width 250dp in the FrameLayout and then draw a white square with width 150dp in the FrameLayout. Since the white square comes after the red square, the white square will be drawn on top of the red square.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android=""
    android:orientation="vertical" >

    <!-- kvarela: Red square -->
        android:background="#FFFF0000" />

    <!-- kvarela: White square -->
        android:background="#FFFFFFFF" />

Here’s a screen shot:

FrameLayout Example
FrameLayout Example