为啥 Ionic 键盘事件不触发?
Posted
技术标签:
【中文标题】为啥 Ionic 键盘事件不触发?【英文标题】:Why are the Ionic keyboard events not firing?为什么 Ionic 键盘事件不触发? 【发布时间】:2018-09-22 11:17:48 【问题描述】:我正在尝试在键盘弹出和隐藏时执行一些代码。我将它放在主 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');
);
);
我尝试过使用 ionic-native 的 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 上测试该应用,它使用默认的三星键盘。
【问题讨论】:
【参考方案1】:您可以使用如下键盘事件;
window.addEventListener('keyboardWillShow', (e) => );
window.addEventListener('keyboardWillHide', () => );
window.addEventListener('keyboardDidShow', (e) => );
window.addEventListener('keyboardDidHide', () => );
【讨论】:
是的,无法让onKeyboardShow()
使用 Ionic 应用程序。改为使用window
对象。【参考方案2】:
对于 Ionic 4 Keyboard Native Plugin 尝试使用 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
【讨论】:
【参考方案3】:在https://github.com/ionic-team/ionic-native/issues/2306 找到答案,在撰写本文时键盘插件似乎有些损坏。
...
import Observable from 'rxjs'
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 为我提供的解决方案!
【讨论】:
以上是关于为啥 Ionic 键盘事件不触发?的主要内容,如果未能解决你的问题,请参考以下文章