Preventing the Android Keyboard from Showing on Page Load in NativeScript App

Background

This comes up from time to time and there are several approaches to resolve it and several approaches to prevent it from happening in the first place with an Android application.

This post is just a reminder to myself and others for a succinct way to prevent the Android keyboard from showing on page load when a textfield is present.

Solution

I prefer to do this in the onNavigatedTo or the loaded event of the Page.

import * as app from 'application';
declare var android: any; //bypass the TS warnings
if (isAndroid) {
     // prevent the soft keyboard from showing initially when textfields are present
     app.android.startActivity.getWindow().setSoftInputMode(
     android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
 }

That is it! You’ll now prevent the soft keyboard from showing when you open a page in your Android NativeScript app that has a textfield. It’s calling this native method: https://developer.android.com/reference/android/view/Window.html#setSoftInputMode(int) for reference. Again, this is the amazing power that NativeScript provides. Direct access to native Android and iOS APIs.

SearchBar Focus

I answered a question on StackOverflow about the focus being a SearchBar and here is the answer: http://stackoverflow.com/a/37868473/1893557. The code involves getting the parent layout and calling native Android methods for the focusing which prevents the keyboard from showing.


// get the parent of the searchbar
var parent = page.getViewById('searchbarParent');
var searchBar = page.getViewById('searchBar');
if (parent.android) {
    parent.android.setFocusableInTouchMode(true);
    parent.android.setFocusable(true);
    searchBar.android.clearFocus();
}

8 thoughts on “Preventing the Android Keyboard from Showing on Page Load in NativeScript App

  1. Hi Guys, nice tip. It’s helpul… I have one issue. Someone know how to hide Android Navigation Bar when keyboard is opened in fullscreen application (without status bar and navigation)… users can’t close my application on keyboard is opened, any suggestions?

    Like

      1. It’s helpful, i’m running an android application in “Fullscreen immersive mode”, but when keyboard is opened a navigation bar appears too! Do you know how to hide the navigation bar when keyboard is opened?

        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