Dismiss the Android SoftKeyboard Programmatically in a NativeScript App

Be Gone You Damn KeyBoard

If you’re like me you get really frustrated with apps that leave the soft keyboard open when you’ve completed some action that should have closed it. Maybe you completed a form and tapped a ‘Submit’ button, well that keyboard is pointless now so hide the thing please. There are some use cases where you don’t want to but oh well I’m going to tell you how to get rid of it when you want to in your code.


import * as app from 'application';

import { isAndroid } from 'platform';

/**
* Hide the keyboard with a conditional Android platform check.
*/
private hideKeyboard() {

   if (isAndroid) {
      try {
         let activity = app.android.foregroundActivity;
         let Context = app.android.currentContext;
         let inputManager = Context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), android.view.inputmethod.InputMethodManager.HIDE_NOT_ALWAYS);
      } catch (err) {
         console.log(err);
      }
}
}

The code is pretty simple and just uses the Android InputMethodManager service and calls the hideSoftInputFromWindow() method. Has worked great in my apps and hopefully it helps you out if you ever need to get rid of the keyboard in your Android NativeScript app.

 

13 thoughts on “Dismiss the Android SoftKeyboard Programmatically in a NativeScript App

    1. So the activity.getCurrentFocus() method isn’t working I guess. Might be worth debugging this one. I have this in an app in production so I’m guessing something changed on the nativescript side with the activity or the API call isn’t available on the Android device you’re getting this error on. If that doesn’t help an issue on GitHub for the core team would help since this might hit others who won’t see this blog post. Thanks for reading anyway, sorry you have the issue right now

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s