Search code examples
nativescript

Nativescript Android - hide keyboard


In my Nativescript app, the application starts with the login page. On iOS everything looks good, but on android, the username field is focused and the keyboard is showing. Is there a way to prevent this from happening?

So far I have tried:

  • Getting a reference of another element (a label) and calling lbl.focus() in the page's onLoaded event
  • getting a reference of the username textfield and calling txt.dismissSoftInput() and txt.android.clearFocus()

None of this worked. Is there another way to hide the keyboard when the page is loaded?

Thank you


Solution

  • So I ended up implementing a different solution. This may not be the best approach, but it serves its purpose in my case and I wanted to share it for those of you that face a similar scenario.

    in page's loaded event I included this code:

        if (page.android) {
            var un = page.getViewById('username');
            var p = page.getViewById('password');
            un.android.setFocusable(false);
            p.android.setFocusable(false);
            setTimeout(function () {
                un.android.setFocusableInTouchMode(true);
                p.android.setFocusableInTouchMode(true);
            }, 300);
        }

    The key here is the setTimeout function (Thanks Emil Oberg for pointing me to the right direction). As far as I understand, here is what is happening:

    • The page loads and we call setFocusable(false) on the only 2 text fields to prevent Android from setting the focus on them
    • Then we wait 300ms to allow Android to do its initialization
    • When the timeout executes, call setFocusableInTouchMode(true) to allow the fields to gain focus.

    At this point the page is loaded without any fields to be in focus and with the keyboard hidden. If the user taps any of the fields the keyboard will appear and they can proceed to log in as usual.

    As I mentioned, this may not be the best, or correct, approach, but works for me. Hope this can save someone the time to research the issue.