Developer

Pro tip: Use the IME manager to show and hide Android's virtual keyboard

See how simple it is to show and hide the Android virtual keyboard when appropriate by using the input method (IME) manager.

android-040714.jpg

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
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.authorwjf.kbdtoggled"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" 
            android:windowSoftInputMode="adjustResize|stateHidden" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

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
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/hide_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="Hide VKB" />
    
    <EditText
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    
    <Button
        android:id="@+id/show_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="Show VKB" />

</LinearLayout>

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

androidvkb091714.png

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.

About William J. Francis

William J Francis began programming computers at age eleven. Specializing in embedded and mobile platforms, he has more than 20 years of professional software engineering under his belt, including a four year stint in the US Army's Military Intellige...

Editor's Picks

Free Newsletters, In your Inbox