參考資料:https://blog.csdn.net/genglanggenglang/article/details/77679245
一:修改app.html頁面
添加 #myNav
二:修改tabs.html頁面
添加#myTabs 參考文檔是#mainTabs,當然你也可以改為其他的,因為我這裡之前已經定義了,是以沒改成參考文檔的名稱。
三:修改tabs.tsl頁面
添加:@ViewChild("myTabs") tabs: Tabs;
四:修改app.component.ts頁面
引用:ViewChild,ToastController, Nav, Keyboard
引用:TabsPage頁面
按照自己需求添加,下面紅框是添加的,其他部分是之前的,隻加紅框缺少的即可!
擷取myNav和定義變量,調用函數
app.component.ts頁面代碼如下:
import { Component, ViewChild } from '@angular/core';
import { Platform, ToastController, Nav, IonicApp, Keyboard} from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { TabsPage } from '../pages/tabs/tabs';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
public rootPage;
backButtonPressed: boolean = false; //用于判斷傳回鍵是否觸發
@ViewChild('myNav') nav: Nav;
constructor(
public platform: Platform,
public toastCtrl: ToastController,
public keyBoard: Keyboard ,
public ionicApp: IonicApp
) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
this.registerBackButtonAction();//注冊傳回按鍵事件
/*===========設定rootPage(此部分代碼根據情況自己添加)===============*/
}
//傳回按鍵處理
registerBackButtonAction() {
this.platform.registerBackButtonAction(() => {
if (this.keyBoard.isOpen()) {
this.keyBoard.close();
}
else {
let activeVC = this.nav.getActive();
let page = activeVC.instance;
//此處if是rootPage為登入頁的情況,else是rootPage為TabsPage(如果不需要判斷登入頁的情況直接用else内的代碼即可)
if (!(page instanceof TabsPage)) {
if (!this.nav.canGoBack()) {
console.log("檢測到在根視圖點選了傳回按鈕");
this.showExit();
}
else {
console.log("檢測到在子路徑中點選了傳回按鈕。");
this.nav.pop();
}
}
else {
let tabs = page.tabs;
let activeNav = tabs.getSelected();
if (!activeNav.canGoBack()) {
console.log('檢測到在 tab 頁面的頂層點選了傳回按鈕。');
this.showExit();
}
else {
console.log('檢測到目前 tab 彈出層的情況下點選了傳回按鈕。');
activeNav.pop();
}
}
}
}, 1);
}
//輕按兩下退出提示框
showExit() {
if (this.backButtonPressed) { //當觸發标志為true時,即2秒内輕按兩下傳回按鍵則退出APP
this.platform.exitApp();
} else {
this.toastCtrl.create({
message: "再按一次退出應用",
duration: 2000,
position: 'bottom'
//cssClass: 'toastcss' //修改樣式(根據需要添加)
}).present();
this.backButtonPressed = true;
setTimeout(() => this.backButtonPressed = false, 2000);//2秒内沒有再次點選傳回則将觸發标志标記為false
}
}
}
效果如下:
——————————(end)——————————