如何在使用Nativescript的Android应用程序中加载页面时显示键盘?

4
我的安卓应用的第一页有一个输入框。我想要的是,当页面加载时,自动显示键盘,而不需要在输入框上点击。

1
因为在发布之前没有看到你做出任何研究的努力,所以被点踩了。在你的页面的onNavigatedTo中,你可以通过id获取输入视图,并将其聚焦,这应该会打开键盘。 - pkanev
1
我尝试过了,但在安卓上无法运行。 - Pavan Vora
2个回答

6

pkanev的评论在iOS上是正确的,即只需聚焦于文本字段,iOS就会打开键盘。

但在Android上,您需要做一些额外的工作--

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);
}

请注意使用setTimeout,在原生Android中也需要这样做。

2
使用NativeScript和Angular在Android上聚焦输入框并触发键盘:
  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);
      }
    }
    

对我来说,只有在非零超时(例如100毫秒)的情况下才能正常工作。 - xuhcc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接