Ionic实现自定义返回按键事件

在 Android 和 Window 平台下,有时候我们需要监听返回按键的事件来进行相应的操作,也就是自定义返回按键事件。下面根据一个例子来讲解如何在 ionic 中自定义返回按键事件。

功能需求

首先看下要通过自定义返回按键事件来实现的需求(均在点击返回键操作之后):

  • 如果键盘打开,则隐藏键盘;
  • 如果显示 ionic 的 Loading 组件(在请求数据的时候),则隐藏 Loading 组件;
  • 如果当前页面是子页面,则返回上个页面;如果是根页面,则提示用户是否退出应用。

具体实现

首先说明下,本示例的 ionic 应用的结构是 tabs 结构。

  1. tabs.html 中的 ion-tabs 定义别名,如 mainTabs
<ion-tabs #mainTabs selectedIndex="1">
	<ion-tab [root]="tab1Root" tabTitle="页面1"></ion-tab>
	<ion-tab [root]="tab2Root" tabTitle="页面2"></ion-tab>
</ion-tabs>

ion-tabs 定义别名的目的是方便通过代码找到 ion-tabs 的实例。

  1. app.component.ts 中进行实现代码编写(实现细节在注释中):
import { Component, ViewChild } from '@angular/core';
import { Nav, Platform, Keyboard, IonicApp, NavController, Tabs, ToastController, Toast } from 'ionic-angular';

@Component({
	templateUrl: 'app.html'
})
export class AppComponent {
	@ViewChild(Nav) nav: Nav; // ion-nav 引用
	backButtonPressed: boolean = false;  // 用于判断返回键是否触发

	constructor(public platform: Platform,
				public ionicApp: IonicApp,
				public toastCtrl: ToastController,
				public keyboard: Keyboard) {

		// 等待平台加载完成之后注册返回按键事件
		this.platform.ready().then(() => {
			this.registerBackButtonAction(); // 注册返回按键事件
		});
	}

	/**
	 * 注册返回按键事件
	 */
	registerBackButtonAction() {

		// 使用 registerBackButtonAction 方法进行自定义事件处理程序
		this.platform.registerBackButtonAction(() => {

			// 如果键盘开启则隐藏键盘。实现要点:使用 ionic-plugin-keyboard 插件进行键盘的控制
			if (this.keyboard.isOpen()) {
				this.keyboard.close();
				return;
			}

			// 隐藏加载动画。实现要点:通过 this.ionicApp._loadingPortal 获取到代表 Loading 的 OverlayPortal,然后获取当前被激活的 ViewController
			const activePortal: any = this.ionicApp._loadingPortal.getActive();
			if (activePortal) { // 如果有被激活的 ViewController 则将其隐藏。
				activePortal.dismiss();
				activePortal.onDidDismiss();
				return;
			}

			// 根据当前导航进行不同的处理( mainTabs 对象是在 TabsPage 定义的 ion-tabs )
			// 通过 this.nav.getActive().instance.mainTabs 获取到别名为 mainTabs 的 ion-tabs
			const mainTabs: Tabs = this.nav.getActive().instance.mainTabs;
			if (mainTabs) {

				// 获取到当前被选中的 ion-tab
				const mainNav: NavController = mainTabs.getSelected();

				// 如果 ion-tab 能返回则返回上一个页面,不能就直接退出应用
				mainNav.canGoBack() ? mainNav.pop() : this.showExit();
			} else {

				// 如果 ion-nav 能返回则返回上一个页面,不能就直接退出应用
				this.nav.canGoBack() ? this.nav.pop() : this.showExit();
			}
			return;
		}, 1);
	}

	/**
	 * 双击退出提示框
	 */
	showExit() {
		if (this.backButtonPressed) { // 当触发标志为 true 时,即2秒内双击返回按键则退出APP
			this.platform.exitApp();
		} else {
			const currentToast: Toast = this.toastCtrl.create({
				message: '再按一次退出应用',
				duration: 2000,
				position: 'top'
			});
			currentToast.present().then(() => {
				this.backButtonPressed = true;

				// 2秒内没有再次点击返回则将触发标志标记为false
				const id: any = setTimeout(() => {
					clearTimeout(id);
					this.backButtonPressed = false;
				}, 2000);
			});
		}
	}
}
posted @ 2018-07-08 12:41  laixiangran  阅读(958)  评论(0编辑  收藏  举报