4

The first page of my android application has one input field. So what I want is when this page loads I want to show keyboard automatically without doing tap on the input field.

Pavan Vora
  • 1,634
  • 14
  • 19
  • 1
    Downvoted for the visible lack of effort in researching the matter before posting. Inside your page's onNavigatedTo you can get the input view by id, and focus it, which should in turn open the keyboard. – pkanev Aug 31 '17 at 18:37
  • 1
    I tried that it's not working in android. – Pavan Vora Sep 06 '17 at 02:38

2 Answers2

6

pkanev's comment is true on ios; ie, just focus on the text field and ios will open up the keyboard.

But on Android you need to do some extra work --

var utils = require("tns-core-modules/utils/utils");

var myTextfield = page.getViewById("myTextFieldId");

if (myTextfield.ios) {
    console.log("myTextfield.ios");

    // on ios this will open the keyboard but not on android
    myTextfield.focus();
}

if (myTextfield.android) {
    console.log("myTextfield.android");

    setTimeout(function() {

        // places the cursor here but doesn't open the keyboard
        myTextfield.android.requestFocus();

        var imm = utils.ad.getInputMethodManager();

        imm.showSoftInput(myTextfield.android, 0);

    }, 300);
}

Notice the use of setTimeout which is what you would need to do in native Android too.

2

To focus the field and trigger the keyboard in Android with NativeScript and Angular:

  1. Name your element in your template: <TextField #myInput [...]></TextField>

  2. Use it in your component file:

    import { ElementRef, OnInit } from "@angular/core";
    
    [...]
    
    export class MyComponent implements OnInit {
      @ViewChild("myInput") myInput: ElementRef;
    
      [...]
    
      ngOnInit() {
        setTimeout(() => this.myInput.nativeElement.focus(), 0);
      }
    }
    
Brendan
  • 868
  • 1
  • 16
  • 38