Android’s virtual keyboard (VKB) has grown over the years to become one of the best predictive soft keyboards on the market. Not only that, but those of us who write Android code for a living rarely have to give keyboard input a second thought thanks to the window soft input mode options Google thoughtfully provided as part of the manifest for each and every activity.

There are a few cases, however, when you may need to manually force the VKB to show or, more likely, hide. A real-world scenario might be the user has the VKB showing when suddenly she decides to tap something in your menu bar that initiates a fragment replace. Those transitions can look pretty nasty with the VKB front and center.

The following example shows a simple method to obtain a reference to the input method (IME) manager, and how to use that reference to show and hide the VKB when appropriate. You can follow along with the step-by-step instructions, or download and import the entire project directly into Eclipse.

1. Create a new Android project in Eclipse. Target SDK 14 (ICS) or better.

2. In the AndroidManifest.xml file, set the initial soft input mode and startup state.

AndroidManifest.xml







3. In the /res/layout folder, modify activity_main.xml to stack two buttons and a text view within a linear layout.

activity_main.xml

4. The only thing left to flesh out is our MainActivity.java file. In the on create override we get a reference to the IME service, and in the on click listener we invoke either the show or the hide method with an appropriate target.

ActivityMain.java
package com.authorwjf.kbdtoggled;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;

public class MainActivity extends Activity implements OnClickListener {

private InputMethodManager mIMEMgr;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mIMEMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
findViewById(R.id.show_button).setOnClickListener(this);
findViewById(R.id.hide_button).setOnClickListener(this);
}

@Override
public void onClick(View v) {
if (v.getId()==R.id.show_button) {
mIMEMgr.showSoftInput(findViewById(R.id.content), 0);
} else {
mIMEMgr.hideSoftInputFromWindow(findViewById(R.id.content).getWindowToken(), 0);
}
}

}

Run the resulting APK on a device or an emulator to see the buttons in action (Figure A).

Figure A

Note: The show/hide soft input methods have a return value and can fail. For instance, calling show with a view that cannot handle input will not work. While this can be annoying at times, it can come in handy. For example, calling hide on an already hidden VKB will fail, thus, essentially giving you a quick method for checking if the VKB is visible.