为什么离子键盘事件没有触发?

时间:2018-04-12 10:30:32

标签: android angular typescript ionic-framework ionic3

当键盘弹出并隐藏时,我试图执行一些代码。我已将它放在主MyAppComponent中,因为我希望代码在任何应用页面上执行,但由于某些原因,没有任何键盘事件正在运行。我做错了什么?

...
import { Keyboard, Platform } from 'ionic-angular';

export class MyAppComponent {

    constructor(public platform: Platform, public keyboard: Keyboard) {
        this.platform.ready().then(() => {

            this.keyboard.didShow.subscribe(() => {
                // This is never executed...
                console.log('Keyboard is now open');
            });
        });
    }
}

我尝试过使用离子原生的onKeyboardShow,但也没有执行其代码。

...
import { Platform } from 'ionic-angular';
import { Keyboard } from '@ionic-native/keyboard';

export class MyAppComponent {

    constructor(public platform: Platform, public keyboard: Keyboard) {
        this.platform.ready().then(() => {

            this.keyboard.onKeyboardShow().subscribe(() => {
                // This is never executed...
                console.log('Keyboard is now open');
            });
        });
    }
}

离子信息转储:

cli packages: (/usr/lib/node_modules)
    @ionic/cli-utils  : 1.19.2
    ionic (Ionic CLI) : 3.20.0

global packages:
    cordova (Cordova CLI) : 8.0.0 

local packages:
    @ionic/app-scripts : 3.1.8
    Cordova Platforms  : android 7.0.0
    Ionic Framework    : ionic-angular 3.9.2

System:
    Android SDK Tools : 26.1.1
    Node              : v9.11.1
    npm               : 5.8.0 
    OS                : Linux 4.13

安装了cordova-plugin-ionic-keyboard插件(版本2.0.5),添加到appModule并显示在config.xml中

我在使用Android 7.0的三星Galaxy S6上测试应用程序,它使用默认的三星键盘。

3 个答案:

答案 0 :(得分:5)

您可以使用如下的键盘事件;

  window.addEventListener('keyboardWillShow', (e) => {}); 
  window.addEventListener('keyboardWillHide', () => {});
  window.addEventListener('keyboardDidShow', (e) => {}); 
  window.addEventListener('keyboardDidHide', () => {});

答案 1 :(得分:1)

https://github.com/ionic-team/ionic-native/issues/2306中找到了一个答案,在撰写本文时,键盘插件似乎有点破碎。

...
import { Platform } from 'ionic-angular';

export class MyAppComponent {

    constructor(public platform: Platform) {
        this.platform.ready().then(() => {

            Observable.fromEvent(window, 'keyboardWillShow').subscribe(() => {
                console.log('Keyboard is now open');
            });
        });
    }
}

感谢https://github.com/ionic-team/ionic-native/issues/2306#issuecomment-372593829提供适合我的解决方案!

答案 2 :(得分:0)

对于 Ionic 4键盘本机插件,请尝试使用 addEventListener

window.addEventListener('keyboardWillShow', () => {
  console.log("Keyboard will Show");
});
window.addEventListener('keyboardDidShow', () => {
  console.log("Keyboard is Shown");
});
window.addEventListener('keyboardWillHide', () => {
  console.log("Keyboard will Hide");
});
window.addEventListener('keyboardDidHide', () => {
  console.log("Keyboard is Hidden");
});

检查完整的教程代码here