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.
What about iOS to close keypad ?
LikeLike
Thank you!
LikeLike
Thanks! Been banging my head on this for a day!
LikeLike
Glad it helped someone out 🙂
LikeLike
Thanks Brad!
LikeLike
hii its not working with the current anngular update
LikeLike
If it’s not working as is – I’d open an issue on the github repo and share your code so the team can fix any bugs 🙂
LikeLike
Great, thanks!
LikeLiked by 1 person
TypeError: Cannot read property ‘getWindowToken’ of null
LikeLike
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
LikeLike
i am using typescript version 2.4.1
LikeLike
Thanks Brad! It helped.
LikeLike
I got this error, “Cannot find name android”
LikeLike
add a
declare let android;
before the function
LikeLike