How to show and hide soft keyboard in Android

Nate Rubin edited this page Apr 8, 2014 · 2 revisions

Original Article here: Create a class that handles the keyboard

import com.phonegap.DroidGap;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;

public class KeyBoard {

        private WebView mAppView;
        private DroidGap mGap;

        public KeyBoard(DroidGap gap, WebView view)
            mAppView = view;
            mGap = gap;

        public void showKeyBoard() {
            InputMethodManager mgr = (InputMethodManager) mGap.getSystemService(Context.INPUT_METHOD_SERVICE);
            // only will trigger it if no physical keyboard is open
            mgr.showSoftInput(mAppView, InputMethodManager.SHOW_IMPLICIT);
            ((InputMethodManager) mGap.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(mAppView, 0);

        public void hideKeyBoard() {
            InputMethodManager mgr = (InputMethodManager) mGap.getSystemService(Context.INPUT_METHOD_SERVICE);
            mgr.hideSoftInputFromWindow(mAppView.getWindowToken(), 0);


In your main activity add a Javascript interface for this class:

import android.os.Bundle;
import com.phonegap.*;

public class Mobile_PG extends DroidGap {
    public void onCreate(Bundle savedInstanceState) {

         KeyBoard keyboard = new KeyBoard(this, appView);
        appView.addJavascriptInterface(keyboard, "KeyBoard");



From the javascript you now can call window.KeyBoard.showKeyBoard(); to show the soft keyboard and if needed you can hide it with window.KeyBoard.hideKeyBoard();

I copy the android_rules.xml file into my build.xml and then ant compile and ant install. This is how the build.xml looks like:

<?xml version="1.0" encoding="UTF-8"?>
<project name="Mobile_PG">

    <!-- The file is created and updated by the 'android' tool.
         It contains the path to the SDK. It should *NOT* be checked in in Version
         Control Systems. -->
    <property file="" />

    <!-- The file can be created by you and is never touched
         by the 'android' tool. This is the place to change some of the default property values
         used by the Ant rules.
         Here are some properties you may want to change/update:

             the name of your application package as defined in the manifest. Used by the
             'uninstall' rule.
             the name of the source directory. Default is 'src'.
             the name of the output directory. Default is 'bin'.

         Properties related to the SDK location or the project target should be updated
          using the 'android' tool with the 'update' action.

         This file is an integral part of the build system for your application and
         should be checked in in Version Control Systems.

    <property file="" />

    <!-- The file is created and updated by the 'android' tool, as well
         as ADT.
         This file is an integral part of the build system for your application and
         should be checked in in Version Control Systems. -->
    <property file="" />

    <!-- Custom Android task to deal with the project target, and import the proper rules.
         This requires ant 1.6.0 or above. -->
    <path id="android.antlibs">
        <pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
        <pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
        <pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
        <pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
        <pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />

    <taskdef name="setup"

    <!-- Execute the Android Setup task that will setup some properties specific to the target,
         and import the build rules files.

         The rules file is imported from

         To customize some build steps for your project:
         - copy the content of the main node <project> from android_rules.xml
         - paste it in this build.xml below the <setup /> task.
         - disable the import by changing the setup task below to <setup import="false" />

         This will ensure that the properties are setup correctly but that your customized
         build steps are used.
    <setup import="false" />
    <!-- Custom tasks -->
    <taskdef name="aaptexec"
        classpathref="/android.antlibs" />

    <taskdef name="apkbuilder"
        classpathref="/android.antlibs" />

    <taskdef name="xpath"
        classpathref="/android.antlibs" />

    <!-- Properties -->

    <!-- Tells adb which device to target. You can change this from the command line
         by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for
         the emulator. -->
    <property name="adb.device.arg" value="" />

    <property name="" location="${sdk.dir}/tools" />
    <!-- Name of the application package extracted from manifest file -->
    <xpath input="AndroidManifest.xml" expression="/manifest/@package"
                output="manifest.package" />

    <!-- Input directories -->
    <property name="source.dir" value="src" />
    <property name="source.absolute.dir" location="${source.dir}" />
    <property name="gen.dir" value="gen" />
    <property name="gen.absolute.dir" location="${gen.dir}" />
    <property name="resource.dir" value="res" />
    <property name="resource.absolute.dir" location="${resource.dir}" />
    <property name="asset.dir" value="assets" />
    <property name="asset.absolute.dir" location="${asset.dir}" />

    <!-- Directory for the third party java libraries -->
    <property name="external.libs.dir" value="libs" />
    <property name="external.libs.absolute.dir" location="${external.libs.dir}" />

    <!-- Directory for the native libraries -->
    <property name="native.libs.dir" value="libs" />
    <property name="native.libs.absolute.dir" location="${native.libs.dir}" />

    <!-- Output directories -->
    <property name="out.dir" value="bin" />
    <property name="out.absolute.dir" location="${out.dir}" />
    <property name="out.classes.dir" value="${out.absolute.dir}/classes" />
    <property name="out.classes.absolute.dir" location="${out.classes.dir}" />

    <!-- Intermediate files -->
    <property name="" value="classes.dex" />
    <property name="intermediate.dex.file" location="${out.absolute.dir}/${}" />

    <!-- The final package file to generate -->
    <property name="out.debug.unaligned.package"
                  location="${out.absolute.dir}/${}-debug-unaligned.apk" />
    <property name="out.debug.package"
                  location="${out.absolute.dir}/${}-debug.apk" />
    <property name="out.unsigned.package"
                  location="${out.absolute.dir}/${}-unsigned.apk" />
    <property name="out.unaligned.package"
                  location="${out.absolute.dir}/${}-unaligned.apk" />
    <property name="out.release.package"
                  location="${out.absolute.dir}/${}-release.apk" />

    <!-- Verbosity -->
    <property name="verbose" value="false" />
    <!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false'
         The property 'verbosity' is not user configurable and depends exclusively on 'verbose'
    <condition property="verbosity" value="verbose" else="quiet">
        <istrue value="${verbose}" />
    <!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose'
    <condition property="v.option" value="-v" else="">
        <istrue value="${verbose}" />
    <!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' -->
    <condition property="verbose.option" value="--verbose" else="">
        <istrue value="${verbose}" />

    <!-- Tools -->
    <condition property="exe" value=".exe" else=""><os family="windows" /></condition>
    <property name="adb" location="${}/adb${exe}" />
    <property name="zipalign" location="${}/zipalign${exe}" />

    <!-- Emma configuration -->
    <property name="emma.dir" value="${sdk.dir}/tools/lib" />
        <path id="emma.lib">
            <pathelement location="${emma.dir}/emma.jar" />
            <pathelement location="${emma.dir}/emma_ant.jar" />
    <taskdef resource="" classpathref="/emma.lib" />
    <!-- End of emma configuration -->

    <!-- Macros -->

    <!-- Configurable macro, which allows to pass as parameters output directory,
         output dex filename and external libraries to dex (optional) -->
    <macrodef name="dex-helper">
       <element name="external-libs" optional="yes" />
       <element name="extra-parameters" optional="yes" />
         <echo>Converting compiled files and external libraries into ${intermediate.dex.file}...
         <apply executable="${dx}" failonerror="true" parallel="true">
             <arg value="--dex" />
             <arg value="--output=${intermediate.dex.file}" />
             <extra-parameters />
             <arg line="${verbose.option}" />
             <arg path="${out.classes.absolute.dir}" />
             <fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
             <external-libs />

    <!-- This is macro that enable passing variable list of external jar files to ApkBuilder
         Example of use:
                <jarfolder path="my_jars" />
                <jarfile path="foo/bar.jar" />
                <jarfolder path="your_jars" />
         </package-helper> -->
    <macrodef name="package-helper">
        <attribute name="sign.package" />
        <element name="extra-jars" optional="yes" />
                <file path="${intermediate.dex.file}" />
                <sourcefolder path="${source.absolute.dir}" />
                <nativefolder path="${native.libs.absolute.dir}" />
                <jarfolder path="${external.libs.absolute.dir}" />

    <!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets
         debug, -debug-with-emma and release.-->
    <macrodef name="zipalign-helper">
        <attribute name="in.package" />
        <attribute name="out.package" />
            <echo>Running zip align on final apk...</echo>
            <exec executable="${zipalign}" failonerror="true">
                <arg line="${v.option}" />
                <arg value="-f" />
                <arg value="4" />
                <arg path="@{in.package}" />
                <arg path="@{out.package}" />

    <!-- This is macro used only for sharing code among two targets, -install and
         -install-with-emma which do exactly the same but differ in dependencies -->
    <macrodef name="install-helper">
            <echo>Installing ${out.debug.package} onto default emulator or device...</echo>
            <exec executable="${adb}" failonerror="true">
                <arg line="${adb.device.arg}" />
                <arg value="install" />
                <arg value="-r" />
                <arg path="${out.debug.package}" />

    <!-- Rules -->

    <!-- Creates the output directories if they don't exist yet. -->
    <target name="-dirs">
        <echo>Creating output directories if needed...</echo>
        <mkdir dir="${resource.absolute.dir}" />
        <mkdir dir="${external.libs.absolute.dir}" />
        <mkdir dir="${gen.absolute.dir}" />
        <mkdir dir="${out.absolute.dir}" />
        <mkdir dir="${out.classes.absolute.dir}" />

    <!-- Generates the file for this project's resources. -->
    <target name="-resource-src" depends="-dirs">
        <echo>Generating / from the resources...</echo>
        <exec executable="${aapt}" failonerror="true">
            <arg value="package" />
            <arg line="${v.option}" />
            <arg value="-m" />
            <arg value="-J" />
            <arg path="${gen.absolute.dir}" />
            <arg value="-M" />
            <arg path="AndroidManifest.xml" />
            <arg value="-S" />
            <arg path="${resource.absolute.dir}" />
            <arg value="-I" />
            <arg path="${android.jar}" />

    <!-- Generates java classes from .aidl files. -->
    <target name="-aidl" depends="-dirs">
        <echo>Compiling aidl files into Java classes...</echo>
        <apply executable="${aidl}" failonerror="true">
            <arg value="-p${android.aidl}" />
            <arg value="-I${source.absolute.dir}" />
            <arg value="-o${gen.absolute.dir}" />
            <fileset dir="${source.absolute.dir}">
                <include name="**/*.aidl" />

    <!-- Compiles this project's .java files into .class files. -->
    <target name="compile" depends="-resource-src, -aidl"
                description="Compiles project's .java files into .class files">
        <!-- If android rules are used for a test project, its classpath should include
             tested project's location -->
        <condition property="extensible.classpath"
                           value="${tested.project.absolute.dir}/bin/classes" else=".">
            <isset property="tested.project.absolute.dir" />
        <javac encoding="ascii" target="1.5" debug="true" extdirs=""
                verbose="${verbose}" classpath="${extensible.classpath}">
            <src path="${source.absolute.dir}" />
            <src path="${gen.absolute.dir}" />
                <fileset dir="${external.libs.absolute.dir}" includes="*.jar" />

    <!-- Converts this project's .class files into .dex files -->
    <target name="-dex" depends="compile">
        <dex-helper />

    <!-- Puts the project's resources into the output package file
         This actually can create multiple resource package in case
         Some custom apk with specific configuration have been
         declared in
    <target name="-package-resources">
        <echo>Packaging resources</echo>
        <aaptexec executable="${aapt}"
                basename="${}" />

    <!-- Packages the application and sign it with a debug key. -->
    <target name="-package-debug-sign" depends="-dex, -package-resources">
        <package-helper sign.package="true" />

    <!-- Packages the application without signing it. -->
    <target name="-package-no-sign" depends="-dex, -package-resources">
        <package-helper sign.package="false" />

    <target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again">
       <subant target="compile">
            <fileset dir="${tested.project.absolute.dir}" includes="build.xml" />

    <!-- Builds debug output package, provided all the necessary files are already dexed -->
    <target name="debug" depends="-compile-tested-if-test, -package-debug-sign"
                description="Builds the application and signs it with a debug key.">
        <zipalign-helper in.package="${out.debug.unaligned.package}"
                                   out.package="${out.debug.package}" />
        <echo>Debug Package: ${out.debug.package}</echo>

    <target name="-release-check">
        <condition property="release.sign">
                <isset property="" />
                <isset property="key.alias" />

    <target name="-release-nosign" depends="-release-check" unless="release.sign">
        <echo>No and key.alias properties found in</echo>
        <echo>Please sign ${out.unsigned.package} manually</echo>
        <echo>and run zipalign from the Android SDK tools.</echo>

    <target name="release" depends="-package-no-sign, -release-nosign" if="release.sign"
                description="Builds the application. The generated apk file must be signed before
                            it is published.">
        <!-- Gets passwords -->
                message="Please enter keystore password (store:${}):"
                addproperty="" />
                message="Please enter password for alias '${key.alias}':"
                addproperty="key.alias.password" />

        <!-- Signs the APK -->
        <echo>Signing final apk...</echo>
                verbose="${verbose}" />

        <!-- Zip aligns the APK -->
        <zipalign-helper in.package="${out.unaligned.package}"
                                   out.package="${out.release.package}" />
        <echo>Release Package: ${out.release.package}</echo>

    <target name="install" depends="debug"
                description="Installs/reinstalls the debug package onto a running
                            emulator or device. If the application was previously installed,
                            the signatures must match." >
        <install-helper />

    <target name="-uninstall-check">
        <condition property="">
           <isset property="manifest.package" />

    <target name="-uninstall-error" depends="-uninstall-check" unless="">
        <echo>Unable to run 'ant uninstall', manifest.package property is not defined.

    <!-- Uninstalls the package from the default emulator/device -->
    <target name="uninstall" depends="-uninstall-error" if=""
                description="Uninstalls the application from a running emulator or device.">
        <echo>Uninstalling ${manifest.package} from the default emulator or device...</echo>
        <exec executable="${adb}" failonerror="true">
            <arg line="${adb.device.arg}" />
            <arg value="uninstall" />
            <arg value="${manifest.package}" />

    <target name="clean" description="Removes output files created by other targets.">
        <delete dir="${out.absolute.dir}" verbose="${verbose}" />
        <delete dir="${gen.absolute.dir}" verbose="${verbose}" />

    <!-- Targets for code-coverage measurement purposes, invoked from external file -->

    <!-- Emma-instruments tested project classes (compiles the tested project if necessary)
             and writes instrumented classes to ${instrumentation.absolute.dir}/classes -->
    <target name="-emma-instrument" depends="compile">
        <echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo>
        <!-- It only instruments class files, not any external libs -->
        <emma enabled="true">
            <instr verbosity="${verbosity}"
            <!-- TODO: exclusion filters on R*.class and allowing custom exclusion from
                 user defined file -->

    <target name="-dex-instrumented" depends="-emma-instrument">
            <arg value="--no-locals" />
            <fileset file="${emma.dir}/emma_device.jar" />

    <!-- Invoked from external files for code coverage purposes -->
    <target name="-package-with-emma" depends="-dex-instrumented, -package-resources">
        <package-helper sign.package="true">
                <!-- Injected from external file -->
                <jarfile path="${emma.dir}/emma_device.jar" />

    <target name="-debug-with-emma" depends="-package-with-emma">
        <zipalign-helper in.package="${out.debug.unaligned.package}"
                                   out.package="${out.debug.package}" />

    <target name="-install-with-emma" depends="-debug-with-emma">
        <install-helper />

    <!-- End of targets for code-coverage measurement purposes -->

    <target name="help">
        <!-- displays starts at col 13
              |13                                                              80| -->
        <echo>Android Ant Build. Available targets:</echo>
        <echo>   help:      Displays this help.</echo>
        <echo>   clean:     Removes output files created by other targets.</echo>
        <echo>   compile:   Compiles project's .java files into .class files.</echo>
        <echo>   debug:     Builds the application and signs it with a debug key.</echo>
        <echo>   release:   Builds the application. The generated apk file must be</echo>
        <echo>              signed before it is published.</echo>
        <echo>   install:   Installs/reinstalls the debug package onto a running</echo>
        <echo>              emulator or device.</echo>
        <echo>              If the application was previously installed, the</echo>
        <echo>              signatures must match.</echo>
        <echo>   uninstall: Uninstalls the application from a running emulator or</echo>
        <echo>              device.</echo>
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.