参考资料: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)——————————