在Ionic2項目結構解析中,我們知道在 src/app/app.component.ts 初始化項目,因此我們可以在這里監聽Android返回按鍵,實現雙擊退出應用。
Ionic2 Platform中提供了監聽返回按鍵的API registerBackButtonAction(callback, PRiority),
| 參數 | 類型 | 描述 |
|---|---|---|
| callback | Function | 返回鍵觸發時執行的方法 |
| priority | number | 優先級,優先級高的會先執行,默認為0 |
修改src/app/app.component.ts如下:
import { Component, ViewChild } from '@angular/core';import { Platform, ToastController, Nav } from 'ionic-angular';import { StatusBar, Splashscreen } from 'ionic-native';import { TabsPage } from '../pages/tabs/tabs';@Component({ templateUrl: 'app.html'})export class MyApp { rootPage = TabsPage; backButtonPressed: boolean = false; //用于判斷返回鍵是否觸發 @ViewChild(Nav) nav: Nav; constructor(public platform: Platform, public toastCtrl: ToastController) { this.initializeApp(); } initializeApp() { this.platform.ready().then(() => { StatusBar.styleDefault(); Splashscreen.hide(); //注冊返回按鍵事件 this.platform.registerBackButtonAction((): any => { let activeVC = this.nav.getActive(); let page = activeVC.instance; if (!(page instanceof TabsPage)) { if (!this.nav.canGoBack()) { //當前頁面為tabs,退出APP return this.showExit(); } //當前頁面為tabs的子頁面,正常返回 return this.nav.pop(); } let tabs = page.tabs; let activeNav = tabs.getSelected(); if (!activeNav.canGoBack()) { //當前頁面為tab欄,退出APP return this.showExit(); } //當前頁面為tab欄的子頁面,正常返回 return activeNav.pop(); }, 101); }); } //雙擊退出提示框,這里使用Ionic2的ToastController showExit() { if (this.backButtonPressed) this.platform.exitApp(); //當觸發標志為true時,即2秒內雙擊返回按鍵則退出APP else { let toast = this.toastCtrl.create({ message: '再按一次退出應用', duration: 2000, position: 'bottom' }); toast.present(); this.backButtonPressed = true; //2秒內沒有再次點擊返回則將觸發標志標記為false setTimeout(() => { this.backButtonPressed = false; }, 2000) } }}修改 src/pages/tabs/tabs.html
<ion-tabs #mainTabs> <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab> <ion-tab [root]="tab2Root" tabTitle="About" tabIcon="information-circle"></ion-tab> <ion-tab [root]="tab3Root" tabTitle="Contact" tabIcon="contacts"></ion-tab></ion-tabs>修改 src/pages/tabs/tabs.ts
import { Component,ViewChild } from '@angular/core';import { Tabs } from 'ionic-angular';import { HomePage } from '../home/home';import { AboutPage } from '../about/about';import { ContactPage } from '../contact/contact';@Component({ templateUrl: 'tabs.html'})export class TabsPage { @ViewChild('mainTabs') tabs:Tabs; //根據html中的'#mainTabs'獲取Tabs實例 tab1Root: any = HomePage; tab2Root: any = AboutPage; tab3Root: any = ContactPage; constructor() { }}轉自https://dpary.github.io/2016/12/19/
新聞熱點
疑難解答