Android: Hide a view when the soft keyboard is showing

This took far too long to find, mostly because the documentation doesn’t make sense (to me) and because the one hit on the android-developers list looked like the wrong answer, when it fact it’s right.

On the NPR News for Android app, we have a player at the bottom of the screen. This is handled with a FrameLayout in activity layouts. For activities that had an EditText field, the keyboard would push the player up and cover the important parts of the screen. See the image at right for the ‘before’ issue.

I can see this being a major problem for apps that host a banner ad at the bottom of pages (and saw a post on StackOverflow to that effect). Clearly you don’t want the ad to cover the content when your user is trying to type.

The solution was simple enough for us: mark the activity with windowSoftInputMethod = adjustPan in the Manifest and this resolved it.

    <activity
      android:name="SearchResultsActivity"
      android:windowSoftInputMode="adjustPan"/>

Unfortunately, windowSoftInputMethod is not very well documented. The reference says that there are two possible choices, adjustPan and adjustResize and that activities should always select one or the other.

adjustResize
The activity’s main window is always resized to make room for the soft keyboard on screen.
adjustPan
The activity’s main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desirable than resizing, because the user may need to close the soft keyboard to get at and interact with obscured parts of the window.

What should be made more clear is that “resize” doesn’t mean scale or zoom here, it means that the container for your layout is compressed and every element is realigned to try to make it fit best. While this may make sense for applications that have content above or below the edit field that they want visible while editing, it isn’t what we were looking for.

By using adjustPan the layout manager leaves the activity as it was and only shows a portion of it — the part that would be visible if the keyboard were laid over the activity. Exactly what we want.